如何使用其他对象的方法/如何通过正确的上下文?

时间:2015-10-30 12:52:53

标签: php

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

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

2 个答案:

答案 0 :(得分:2)

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

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,您可以在其中扩展对象。

答案 1 :(得分:1)

你没有扩展基类而且你有一个错字。您也没有调用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();