【问题标题】:PHP __get overload returns array instead of objectPHP __get 重载返回数组而不是对象
【发布时间】:2011-11-08 23:03:52
【问题描述】:

为什么这会返回一个数组而不是一个对象,我怎样才能返回一个对象?

Class MyClass {
    private $filename = '...';
    private $_ini_array;

    public function __construct() {
        // Get the config file data
        $ini_array = parse_ini_file( $filename, true );
        $this->_ini_array = $ini_array;
    }

    public function __get( $param ) {
        return $this->_ini_array[ $param ];
    }
}

被...调用

$c = new MyClass();
var_dump( $c->db_pgsql );

返回...

array(6) {
  ["data"]=>
  string(4) "test"
  ...

并由...铸造

return (object) $this->_ini_array;

返回...

object(stdClass)#2 (6) {
  ["data"]=>
  string(4) "test"
  ...

虽然我想回来......

object(MyClass)#2 (6) {
  ["data"]=>
  string(4) "test"
  ...

非常感谢!

更新。解决了。​​

我最终编写了以下课程,几乎可以实现我的目标。如果您发现任何不良习惯,草率代码等,请发表评论。

class Config {
    private $config_filename = '../include/config.ini';


    public function __construct( array $array=null ){
        if ( $array ) {
            foreach ( $array as $key => $val ) {
                $this->$key = $val;
            }
        } else {
            $ini_array = parse_ini_file( $this->config_filename, true );

            foreach( $ini_array as $key => $val ){
                $this->$key = new self( $val );
            }
        }
    }


    public function __get( $param ) {
        return $this->$param;
    }
}

使用我的特定测试配置文件,生成一个看起来像...的对象

VarDump: object(Config)#1 (3) {
    ["config_filename:private"]=>
    string(21) "../include/config.ini"
    ["heading1"]=>
    object(Config)#2 (3) {
        ["config_filename:private"]=>
        string(21) "../include/config.ini"
        ["str1"]=>
        string(4) "test"
        ["str2"]=>
        string(5) "test2"
    }
    ["heading2"]=>
    object(Config)#3 (2) {
        ["config_filename:private"]=>
        string(21) "../include/config.ini"
        ["str1"]=>
        string(9) "testagain"
    }
}

我宁愿不要像以前那样递归地复制 ["config_filename:private"] 属性。但我想不出办法。因此,如果您知道解决方法,我将不胜感激。

感谢所有帮助我找到正确的方向。

【问题讨论】:

  • _ini_array[db_pgsql] 何时设置?

标签: php arrays oop


【解决方案1】:

为什么这会返回一个数组而不是一个对象[...]

我看到设置$this->_ini_array 的唯一内容是parse_ini_file 的返回值,它返回一个数组(数组的数组)。

我怎样才能返回一个对象?

您需要遍历相关数组并手动填充对象。

【讨论】:

  • 执行此操作的基本代码是什么?除了 stdClass 对象,我不知道如何返回任何东西。
  • 只需创建一个new WhatEverClass(),用数据填充并返回。
  • 在过去的四个小时里,我已经尝试过,但失败了。我似乎无法将上面的内容转换为简单地生成一个可以返回 ini 文件的对象表示的类。我想我只是在我的头上。我离能够将数组数组转换为对象有多近?非常感谢。
【解决方案2】:

根据您的代码,您正在解析一个 ini 文件,然后返回结果数组的一个元素。根据您的调用代码,您期望使用 'db_pgsql' 作为键返回一些值,这将是一个字符串。

如果你想要一个对象,你必须实例化一个对象然后返回它,比如:

class Bar
{
}

class Foo
{

    public function __get($param)
    {
        return new $param();
    }
}

$foo = new Foo();
var_dump($foo->Bar);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 2021-05-20
    • 2020-04-11
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多