我正在尝试如何在PHP中存储字符串资源的配方,但我似乎无法让它工作。我有点不确定 __get 函数相对于数组和对象的工作方式。
错误消息:"致命错误:无法在第 34 行的/var/www/html/workspace/srclistv2/Resource 中使用类型为 stdClass 的对象作为数组.php"
我做错了什么?
/**
* 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;
}