我正在尝试一个关于如何在 PHP 中存储字符串资源的方法,但我似乎无法让它工作。我有点不确定 __get 函数如何与数组和对象相关。
错误消息:“ fatal error :无法将 stdClass 类型的对象用作/var/www/html/workspace/srclistv2/Resource.php 中第 34 行的数组”
我做错了什么?
/**
* 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
。所以在你的__get
你应该做的方法:
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;
}
关于php - __在 PHP "Cannot use object of type stdClass as array"中获取资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13512817/