__获取PHP中的资源";无法将stdClass类型的对象用作数组;
我正在尝试一个如何在PHP中存储字符串资源的方法,但我似乎无法让它工作。我有点不确定_uget函数如何与数组和对象相关 错误消息:“致命错误:无法在第34行的/var/www/html/workspace/srclistv2/Resource.php中将stdClass类型的对象用作数组” 我做错了什么__获取PHP中的资源";无法将stdClass类型的对象用作数组;,php,arrays,object,hash,resources,Php,Arrays,Object,Hash,Resources,我正在尝试一个如何在PHP中存储字符串资源的方法,但我似乎无法让它工作。我有点不确定_uget函数如何与数组和对象相关 错误消息:“致命错误:无法在第34行的/var/www/html/workspace/srclistv2/Resource.php中将stdClass类型的对象用作数组” 我做错了什么 /** * Stores the res file-array to be used as a partt of the resource object. */ class Resource
/**
* Stores the res file-array to be used as a partt of the resource object.
*/
class Resource
{
var $resource;
var $storage = array();
public function __construct($resource)
{
$this->resource = $resource;
$this->load();
}
private function load()
{
$location = $this->resource . '.php';
if(file_exists($location))
{
require_once $location;
if(isset($res))
{
$this->storage = (object)$res;
unset($res);
}
}
}
public function __get($root)
{
return isset($this->storage[$root]) ? $this->storage[$root] : null;
}
}
以下是名为QueryGenerator.res.php的资源文件:
$res = array(
'query' => array(
'print' => 'select * from source prints',
'web' => 'select * from source web',
)
);
这就是我想称之为的地方:
$resource = new Resource("QueryGenerator.res");
$query = $resource->query->print;
确实,您将
$storage
定义为类中的数组,但随后在load
方法中将对象分配给它($this->storage=(object)$res;
)
可以使用以下语法访问类的字段:$object->fieldName
。因此,在您的方法中,您应该:
public function __get($root)
{
if (is_array($this->storage)) //You re-assign $storage in a condition so it may be array.
return isset($this->storage[$root]) ? $this->storage[$root] : null;
else
return isset($this->storage->{$root}) ? $this->storage->{$root} : null;
}
@ElzoValugi当然,是的。我之所以使用此函数,是因为我认为“非php”程序员更容易理解。@PLB:使用此函数返回NULL(来自检查的“else”部分)。仍然使用“$resource->query->print”,就好像它是一个带有字符串的标量。@JonasBallestad您可以像这样访问它:
$resource->query['print']
@PLB所以这意味着使用(object)$res只“对象化”顶层,但将底层保留在数组行为中?@JonasBallestad Yes,当$res
是一个数组时,它的确切行为。