How can I call a method of an object passed as a parameter in PHP?
This is the first class defined in thefirstclass.php
class TheFirstClass {
private $_city='Madrid';
public function city() {
return $_city
}
}
This is the second class defined in thesecondclass.php
class TheSecondClass {
public function myMethod($firstClassObject) {
echo "City: " . $firstClassObject->city(); // <- Why This method doesn´t work?
}
}
And finally, this is
include_once “class/thefirstclass.php”;
include_once “class/thesecondclass.php”;
$firstClassObject = new TheFirstClass();
$secondClassObject = new TheSecondClass();
$secondClassObject->myMethod($firstClassObject);
The problem doesn’t lie in the call to
TheFirstClass::citywithinTheSecondClass::myMethod, but rather thatTheFirstClass::cityreturns a local variable ($_city) rather than an instance variable ($this->_city). Unlike in languages such as C++, in PHP instance variables must always be accessed through an object, even in methods.This is the working code: