如何使用其他对象的方法/如何传递正确的上下文


How use method from other object /How pass right context?

class Person_Writer {
    function writeName (  ){
       echo $this ->name;
    }
    function writeAge ( ){
        echo $this ->age;
    }
}
class Person {
    function __construct($name,$age) {
        $this->writer = new Person_Writer;
        $this->name= $name;
        $this->age = $age;
    }
    function __call($name, $arguments) {          
        $writter = $this->writer;
        call_user_func(array($this->writer, 'WriteName'));
        //  call_user_func(array(new Person_Writer, 'WriteName'));
    }
} 
$obj = new Person('sasha',28);        
$obj->writeName();

错误:注意:未定义的属性:Person_Writer::$name in

如何使用其他对象的方法/如何传递正确的上下文?
我想在$obj中使用函数 writeName ( (。

我不太确定您要在那里做什么,如果您想调用另一个对象的函数,这将起作用:

class Person_Writer {
    function writeName ($name){
        echo $name;
    }
    function writeAge ($age){
        echo $age;
    }
}
class Person{
    function __construct($name,$age) {
        $this->writer = new Person_Writer;
        $this->name= $name;
        $this->age = $age;
    }
    function __call($name, $arguments) {
        $writer = $this->writer;
        $writer->writeName($this->name);
    }
} 
$obj = new Person('sasha',28);
$obj->writeName();

为什么要在Persone_Writer对象中使用$this>名称?此对象将不知道 Person 对象的变量,这就是您收到未定义错误的原因。

编辑:另一种解决方案是Hexana,您可以在其中扩展对象。

您没有扩展基类,并且您有一个拼写错误。 你也没有调用 writeAge(( 方法。 下面对我有用:

class Person_Writer {
public function writeName (  ){
    echo $this ->name;
}
function writeAge ( ){
    echo $this ->age;
}
}
class Person extends Person_Writer{
    function __construct($name,$age) {
        $this->writer = new Person_Writer;
        $this->name= $name;
        $this->age = $age;
    }
    function __call($name, $arguments) {
        $writer = $this->writer;
       call_user_func(array($this->writer, 'WriteName'));
      //  call_user_func(array(new Person_Writer, 'WriteName'));
    }
} 
$obj = new Person('sasha',28);
$obj->writeName();
echo '<br>';
$obj->writeAge();