I am trying to learn OOP PHP so much of this is new to me. I have seen other posts but havent found one that answers my question.
class Test { public function a(){ //getting data... return $array; } public function b($array){ return true; } } $test = new Test(); $x = $test->a()->b();
When I attempt the above I get the following error:
Fatal error: Uncaught Error: Call to a member function a() on array
Can someone explain why this doesnt work? a
returns
an array
and b
accepts an array
.
Advertisement
Answer
In order to do what you’re trying to do here, you’d need to use this instead:
$x = $test->b($test->a());
The second arrow in the expression
$x = $test->a()->b();
attempts to call an object method on the return value of $test->a()
, which is an array as you know. It does not pass the return value of a()
as an argument to b()
.
In order to use a syntax like ->a()->b()
, a()
must return an object with a method b()
. If the method b()
is a method from the same object, you can do that by returning $this
in a()
, but if it also needs to return an array, that won’t work, so you won’t be able to chain the methods like this.
It is possible to make it work if a()
doesn’t return the array, but instead stores in in an object property, and b()
doesn’t take an array, but instead operates on the data in the property.
class Test { protected $data; public function a() { //getting data... $this->data = $theDataYouGot; return $this; } public function b($array) { // do something with $this->data return true; } }
Personally I try to avoid this sort of thing because I think it adds unnecessary complexity and makes testing more difficult without much added benefit, but I have seen it done.