dongzhuo5425 2015-08-05 21:19
浏览 46
已采纳

是否可以将类对象视为变量?

Is it possible to treat class object like a variable ???

What i know we can treat it like a function:

class hello{
    public function __invoke(){
        return ['one','two','three'];
    }
}

$obj = new hello;
var_export($obj()); //returns the defined array ['one','two','three']

What i need to do is to do it with out the (): means treat it like a variable & make it return an (array or another object)

$obj = new hello;
var_export($obj); //returns the defined array ['one','two','three']

Is there any magic method like __invoke() to do this... or even a hacky way to do it ???

  • 写回答

2条回答 默认 最新

  • dragon7713 2015-08-05 21:43
    关注

    No, it's not possible to do that because one can't extent built-in things like array. There are some ways to achieve parts of what you want though:

    Printing out custom data on var_dump()

    This is a feature was introduced in PHP 5.6 with the __debugInfo() magic method.

    class Hello {
        public function __debugInfo(){
            return ['one','two','three'];
        }
    }
    
    var_dump(new Hello);
    

    This would output:

    object(Hello)#1 (3) {
      [0]=>
      string(3) "one"
      [1]=>
      string(3) "two"
      [2]=>
      string(5) "three"
    }
    

    Acting like an array

    While you can't make your objects be an array (that is, extend it), they can behave like arrays if you implement the ArrayAccess interface:

    class Hello implements ArrayAccess {
        private $data = [];
        public function offsetExists($offset) {
            return isset($this->data[$offset]);
        }
        /* insert the rest of the implementation here */
    }
    

    And then you can use it like an array:

    $fake_array = new Hello();
    $fake_array['foo'] = 'bar';
    echo $fake_array['foo'];
    

    Note that you can't pass classes that implement this interface into methods hinted with array.


    It is not possible to act like any other primitive data type unfortunately. If you want ultimate flexibility, you will have to look at things like Python and Scala. In PHP you will need to use some pattern like a getData() and setData() interface for the wrapping object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线