在PHP中将对象作为参数传递时如何访问对象方法?

时间:2011-11-25 11:05:00

标签: php oop

如何在PHP中调用作为参数传递的对象的方法?

这是thefirstclass.php

中定义的第一个类
class TheFirstClass {

    private $_city='Madrid';

    public function city() {
        return $_city
    }   
}

这是在secondcondclass.php中定义的第二个类

class TheSecondClass {

    public function myMethod($firstClassObject) {

        echo "City: " . $firstClassObject->city(); // <- Why This method doesn´t work?      

    }
}

最后,这是     include_once“class / thefirstclass.php”;     include_once“class / thesecondclass.php”;

$firstClassObject = new TheFirstClass();
$secondClassObject = new TheSecondClass();

$secondClassObject->myMethod($firstClassObject);

1 个答案:

答案 0 :(得分:1)

问题不在于TheFirstClass::cityTheSecondClass::myMethod的调用,而是TheFirstClass::city返回局部变量($_city)而不是实例变量( $this->_city)。与C ++等语言不同,PHP实例变量必须始终通过对象访问,即使在方法中也是如此。

这是工作代码:

class TheFirstClass {
    private $_city = "a";

    public function city() {
        return $this->_city;
    }   
}

class TheSecondClass {
    public function myMethod($firstClassObject) {
        echo "City: " . $firstClassObject->city(); // <- Why This method doesn´t work?
    }
}

$test = new TheFirstClass();
$test2 = new TheSecondClass();
$test2->myMethod($test);