2010-06-29 142 views
3

这里是我的代码:PHP:OOP中的变量范围?

class Manual extends controller { 

    function Manual(){ 
     parent::Controller(); 
    $myVar = 'blablabla'; 


    } 

    function doStuff(){ 
     echo $myVar; // Doesn't work. 
    } 

} 

我已经试过各种方法,使其工作,但我不能让我的头周围。我能做什么?

感谢

+1

小提示(如果这是PHP5):代替'function Manual'使用'function __construct'而不是'parent :: Controller()'使用'parent :: __ construct()' – nickf 2010-06-29 23:18:10

回答

8

在你的代码,$myVar是本地的每一个方法。

也许你的意思是$this->myVar?

+1

Yup:'$ this- >当处于对象上下文中时,处于静态上下文中时为'self ::'。 – 2010-06-29 16:52:06

2
function doStuff(){ 
    echo $this->myVar; 
} 
4

您需要使用$ this指针“。

如:

class Test 
{ 
    protected $var; 

    public function __construct() 
    { 
      $this->var = 'foobar'; 
    } 

    public function getVar() 
    { 
      return $this->var; 
    } 
}; 
4
class Manual extends controller { 

    private $myVar; 

    function Manual(){ 
     parent::Controller(); 
     $this->$myVar = 'blablabla'; 
    } 

    function doStuff(){ 
     echo $this->$myVar; 
    } 
} 

更OOP,像二传手/吸气剂

class Manual extends controller { 

    private $myVar; 

    function Manual(){ 
     parent::Controller(); 
     setMyVar('blablabla'); 
    } 

    function doStuff(){ 
     echo getMyVar(); 
    } 

    function getMyVar() { 
     return $this->myVar; 
    } 

    function setMyVar($var) { 
     $this->myVar = $var; 
    } 
2

变量$myVar应该是一类的财产,你不能做:

echo $myVar; 

你应该这样做:

$this->myVar; 
1

书面,$ myVar的是本地的两种方法。

需要声明$ myVar的作为类主体的属性

protected $myVar; 

,然后使用伪变量$ this访问方法的财产,包括构造

$this->myVar; 
1

$myVar字段必须在父类中声明为public/protected或在后代类中声明,并且在您的doStuff()方法中,您必须编写$this->myVar而不是$myVar