【问题标题】:__get resource in PHP "Cannot use object of type stdClass as array"__get 在 PHP 中的资源“不能使用 stdClass 类型的对象作为数组”
【发布时间】:2012-11-10 20:36:15
【问题描述】:

我正在尝试如何在 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;
    }
}

这里是名为 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;

【问题讨论】:

    标签: php arrays object hash resources


    【解决方案1】:

    确实,您在类中将 $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;
    }
    

    【讨论】:

    • @ElzoValugi 当然可以。我使用它是因为我认为对于“非 php”程序员来说更容易理解。
    • @PLB :使用此函数返回 NULL(来自检查的“else”部分)。仍然使用“$resource->query->print”,就好像它是一个带有字符串的标量。
    • @JonasBallestad 您可以通过以下方式访问它:$resource->query['print']
    • @PLB 所以这意味着去 (object)$res 只“对象化”顶层,但保持较低的数组行为?
    • @JonasBallestad 是的,当$res 是一个数组时,它的行为是准确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多