2010-07-21 75 views
-1

我有下面的代码:问题与PHP OOP

class the_class { 
    private the_field; 

    function the_class() { 
    the_field = new other_class(); //has other_method() 
    } 

    function method() { 
    $this->the_field->other_method(); //This doesn't seem to work 
    } 
} 

这有什么错在这里的语法?方法调用似乎总是返回true,就好像方法调用有问题一样。 或者是方法调用所有权利,我应该调试other_method()本身?

TIA,彼得

+0

非常感谢你。完成了! 我是盲人,呃? ;-)对不起。 – 2010-07-21 11:42:39

+0

你仍然可能想接受已花时间回复的人的回答。 – 2010-07-21 16:02:31

回答

3

你已经错过了PHP变量符号和阶级属性的访问:

  • $符号是必须为每个PHP 变量(不是常数)。
  • $this关键字/自变量是必须访问当前类或父类成员。在某些情况下,您可能必须特别针对静态成员使用“自我”或“父母”关键字。

    class the_class { 
        private $the_field;//changes 
    
        function the_class() { 
        $this->the_field = new other_class(); //has other_method()//changes 
        } 
    
        function method() { 
        $this->the_field->other_method(); //This doesn't seem to work 
        } 
    } 
    
2

你需要使用在构造函数中$this->the_field了。

6

您需要为变量使用美元符号。所以,你的代码将因此成为:

class the_class { 
    private $the_field; 

    function the_class() { 
    $this->the_field = new other_class(); 
    // assigning to $this->... assigns to class property 
    } 

    function method() { 
    $this->the_field->other_method(); 
    } 
}