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!
Peter Bailey
source share