-2

我遇到了“调用非对象上的成员函数”的问题 - 错误。字段 $other_class 不可设置用于将来的操作。如何填充和使用对象 $other_class?谢谢。

    $myclass = new MyClass;

    $other_class = $myclass -> GetOther_Class();
    var_dump($other_class); //Works!

    echo $other_class; //Call to a member function on a non-object - Error

    class MyClass
    {
    private $other_class;

        function __construct()
        {
            $other_class =  new Other_Class; //Fill $other_class
            //I tried also 
            //$this -> other_class = new Other_Class;
        }

        public function GetOther_Class()
        {
            return $other_class;    
        }

        private function Generate()
        {
            $other_class -> SetTitle ("Hello"); 
        }

        public function __toString() 
        {
        $this->Generate();
        }


    }
4

3 回答 3

1

问题是您正在引用$other_class,因此当您尝试在 Get 方法中返回它时,它始终为 null 或 undefined。引用当前类的属性时,需要在其前面加上$this->

class MyClass
{
    private $other_class;

    function __construct()
    {
        $this->other_class =  new Other_Class; //Fill $other_class
        //I tried also 
        //$this -> other_class = new Other_Class;
    }

    public function GetOther_Class()
    {
        return $this->other_class;    
    }

    private function Generate()
    {
        $this->other_class -> SetTitle ("Hello"); 
    }

    public function __toString() 
    {
        $this->Generate();
    }
}
于 2013-06-25T13:26:21.787 回答
0

您的错误是因为以下方法失败。当你echo做某事时,它会调用该__toString()方法。

    private function Generate()
    {
        $other_class -> SetTitle ("Hello"); 
    }

尝试将其更改为

    private function Generate()
    {
        $this->other_class -> SetTitle ("Hello"); 
    }

以及在构造函数中

   function __construct()
    {
        $this -> other_class = new Other_Class;
    }

    public function GetOther_Class()
    {
        return $this->other_class;    
    }
于 2013-06-25T13:27:06.447 回答
0
    public function GetOther_Class()
    {
        return $other_class;    
    }

在这部分中,您返回$other_class不存在的本地,您应该返回$this->other_class

于 2013-06-25T13:29:55.747 回答