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 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面