Calling an object inside a function

So, I do not have OOP in PHP.

Here is my problem. I have an object from which I can call a function, and it returns back. So here is the code.

$obj = new OBJ(); function go($url){ $array = $obj->grabArray($url); echo $array['hits']; } go('http://www.mysite.com/hello'); 

It gives me an error

Fatal error: calling grabArray () member function for non-object

+6
function oop php
source share
1 answer

This is not a problem with OOP, it is a problem with a scope. $ obj does not appear inside the go () function. You either need to pass it as a parameter, or enter it into the scope with the global keyword (not recommended)

Recommended Method

 $obj = new OBJ(); go('http://www.mysite.com/hello', $obj); function go( $url, $object ) { $array = $object->grabArray($url); echo $array['hits']; } 

Not recommended

 $obj = new OBJ(); go('http://www.mysite.com/hello'); function go( $url ) { global $obj; $array = $object->grabArray($url); echo $array['hits']; } 

Another solution, similar to the concept of OOP composition, is to make the go () function responsible for instantiating the OBJ.

 go('http://www.mysite.com/hello'); function go( $url ) { $obj = new OBJ(); $array = $obj->grabArray($url); echo $array['hits']; } 

This is probably not ideal, but since you created a new OBJ instance every time you executed go (). You can fix this by "caching" the OBJ instance inside go () with a static variable

 function go( $url ) { static $obj; if ( is_null( $obj ) ) { $obj = new OBJ(); } $array = $obj->grabArray($url); echo $array['hits']; } 

But this approach, similar to composition, is really useful if you do not use your OBJ instance anywhere else than the go () function - if you use it elsewhere, then the parameter approach is the best choice.

All about choosing the right solution for this task!

+35
source share

All Articles