在PHP中将对象作为参数传递时,如何访问对象方法?
如何调用PHP中作为参数传递的对象的方法 这是firstclass.php中定义的第一个类在PHP中将对象作为参数传递时,如何访问对象方法?,php,oop,Php,Oop,如何调用PHP中作为参数传递的对象的方法 这是firstclass.php中定义的第一个类 class TheFirstClass { private $_city='Madrid'; public function city() { return $_city } } 这是secondclass.php中定义的第二个类 class TheSecondClass { public function myMethod($firstCla
class TheFirstClass {
private $_city='Madrid';
public function city() {
return $_city
}
}
这是secondclass.php中定义的第二个类
class TheSecondClass {
public function myMethod($firstClassObject) {
echo "City: " . $firstClassObject->city(); // <- Why This method doesn´t work?
}
}
问题不在于调用
第二类::myMethod
中的第一类::city
,而是第一类::city
返回一个局部变量($\u city
),而不是一个实例变量($this->\u 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);
对第一个类进行分类{
私人$_city=“a”;
公共职能城市(){
返回$this->\u城市;
}
}
第二类{
公共函数myMethod($firstClassObject){
echo“City:”.$firstClassObject->City();//myMethod($test);
你能解释一下什么是无效的吗?也许我喝得太醉了,但应该是这样。@jlb我在这里看不到方法链接。这是对代码的简化,用一个简短的例子清楚地解释了这个问题。$\u city变量确实有一个值,但当我调用$firstClassObject->city()时,方法city()什么也不返回在第二个对象方法中,可能是因为我在传递参数时出错。@bazmegakapa我发誓我在那里看到了它。.我的错!关于返回$this->\u city
?:)这是一个很好的例子,说明为什么它是在开发环境中启用错误报告的一个很好的理由,并注意(甚至注意到通知).我相信如果你有。。。
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);