调用函数内的对象 [英] Call an Object inside of a function
问题描述
$ obj = new OBJ();
函数go($ url){
$ array = $ obj-> grabArray($ url);
echo $ array ['hits'];
}
go('http://www.mysite.com/hello');
这给我错误
致命错误:调用一个非对象的成员函数grabArray()
这不是一个OOP问题,它是一个范围问题。 $ obj在函数go()中不可见。您或者需要将其作为参数传递给它,或者使用global关键字将其引入函数的作用域(不推荐)。
推荐方法
$ obj = new OBJ();
go('http://www.mysite.com/hello',$ obj);
函数go($ url,$ object)
{
$ array = $ object-> grabArray($ url);
echo $ array ['hits'];
}
不推荐的方式
$ obj = new OBJ();
去('http://www.mysite.com/hello');
函数go($ url)
{
global $ obj;
$ array = $ object-> grabArray($ url);
echo $ array ['hits'];
}
还有另一种类似于OOP构图概念的解决方案 - 负责创建OBJ实例的go()函数。
go('http://www.mysite.com/你好');
函数go($ url)
{
$ obj = new OBJ();
$ array = $ obj-> grabArray($ url);
echo $ array ['hits'];
}
然而,这可能并不理想,因为您会创建一个全新的OBJ实例每次执行go()。你可以通过用一个静态变量缓存OBJ内部的实例来解决这个问题。
function go($ url)
{
static $ obj;
if(is_null($ obj))
{
$ obj = new OBJ();
}
$ array = $ obj-> grabArray($ url);
echo $ array ['hits'];
}
但是这种类似组合的方法实际上只在不使用你的OBJ实例除了go()函数之外的其他任何地方 - 如果你确实在其他地方使用它,那么参数方法是最好的选择。
全部是关于选择为手头的任务提供正确的解决方案!
So I'm not to OOP in PHP.
Here is my issue I have a object that I can call a function from and it provides back an arrary. So here is the code.
$obj = new OBJ();
function go($url){
$array = $obj->grabArray($url);
echo $array['hits'];
}
go('http://www.mysite.com/hello');
This gives me the error
Fatal error: Call to a member function grabArray() on a non-object
This is not an OOP issue, it's a scope issue. $obj isn't visible inside the function go(). You either need to pass it in as a parameter, or bring it into the function's scope with the global keyword (not recommended)
Recommended way
$obj = new OBJ();
go('http://www.mysite.com/hello', $obj);
function go( $url, $object )
{
$array = $object->grabArray($url);
echo $array['hits'];
}
Not Recommended way
$obj = new OBJ();
go('http://www.mysite.com/hello');
function go( $url )
{
global $obj;
$array = $object->grabArray($url);
echo $array['hits'];
}
There's another solution which is similar to the OOP concept of composition - you would make the go() function responsible for creating an instance of 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, though, since you'd create a brand new OBJ instance every time you executed go(). You could fix this by "caching" the instance of OBJ 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 composition-like approach is really only useful if you don't use your instance of OBJ anywhere else besides inside the go() function - if you do use it elsewhere, then the parameter approach is the best choice.
It's all about picking the right solution for the task at hand!
这篇关于调用函数内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!