php - __在 PHP "Cannot use object of type stdClass as array"中获取资源

标签 php arrays object hash resources

我正在尝试一个关于如何在 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/

相关文章:

html - Angular 12 - 找不到类型为 '[object Object]' 的不同支持对象 'object'。 NgFor 仅支持绑定(bind)到 Iterables,例如 Arrays

php - Yii 关系在查询中生成 GROUP BY 子句

javascript - 如何在提交时在 PHP 中保存 JavaScript 值存储的序列化数组

ruby-on-rails - Ruby 数组方法 assoc 和 associates 的目的是什么?

javascript - 从数组创建对象,像数组内部一样严格排序

Javascript 对象合并

php - 为学校管理系统设计时间表数据库

php - 我的博客分页不起作用

javascript - 将字符串javascript数组转换为整数javascript数组

python - 如何将字符串对象位置更改为对象