2012-03-05 49 views
0

我在理解OOP中的范围时遇到了一些麻烦。我想要的是$ foo-> test_item()打印 “的TestString” ......现在它只是失败:PHP基础知识:无法处理类内的范围

警告:缺少参数1测试:: test_item()

谢谢很多!

<?php 

class testing { 
    public $vari = "teststring"; 
    function test_item($vari){ //$this->vari doesn't work either 
     print $vari; 
    } 
} 

$foo = new testing(); 
$foo->test_item(); 

?> 

回答

4

test_item()应该是:

function test_item() { 
    print $this->vari; 
} 

不需要通过$vari作为参数。

+0

@Georgo内的变量非常感谢您回答......我知道,这不是那么聪明。我想用这个来测试一下... – Jurudocs 2012-03-05 13:53:15

1

函数的参数不能为 “$这个 - > VAR”,

改变你的类像

class testing { 
    public $vari = "teststring"; 
    function test_item(){ //$this->vari doesn't work either 
     print $this->vari; 
    } 
} 

$foo = new testing(); 
$foo->test_item(); 

阅读该Object-Oriented PHP for Beginners

2

那么,你已经声明了一个方法,期望一个参数,这是缺少的。你应该这样做:

$foo->test_item("Something"); 

至于$this->,那里面的类方法。

function test_item(){ 
    print $this->vari; 
} 
0

发生了什么事还有就是foo- $> test_item()期待的东西作为参数传递,因此,例如

$foo->test_item("Hello"); 

会在这种情况下是正确的。这将打印Hello

,你可能会奇怪,为什么它不打印teststring。这是因为,通过调用

print $vari; 

你只打印已传递至$ foo-变量> test_item()

但是,如果不是你做

function test_item(){ //notice I've removed the argument passed to test_item here... 
    print $this->vari; 
} 

实际上,您将打印类别property $ vari的值。使用$ this - > ...来调用该类范围内的函数或变量。如果你尝试没有$这个 - >然后PHP将查找功能的当地范围