Jon*_*tad 5 php arrays hash resources object
我正在尝试一个关于如何在PHP中存储字符串资源的方法,但我似乎无法让它工作.我对__get函数如何与数组和对象的工作方式有点不确定.
错误消息:"致命错误:不能在第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
{
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是名为QueryGenerator.res.php的资源文件:
$res = array(
'query' => array(
'print' => 'select * from source prints',
'web' => 'select * from source web',
)
);
Run Code Online (Sandbox Code Playgroud)
这是我试图称之为的地方:
$resource = new Resource("QueryGenerator.res");
$query = $resource->query->print;
Run Code Online (Sandbox Code Playgroud)
确实,您$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;
}
Run Code Online (Sandbox Code Playgroud)