如何在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);
答案 0 :(得分:1)
问题不在于TheFirstClass::city
内TheSecondClass::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);