doupi4649 2015-05-30 10:31
浏览 10
已采纳

也可以用作数组的对象

All over the place I have an array with a few elements, for example:

$myItem = [ 'a' => 10, 'b' => 20 ]

But but I would like to replace it with a class

$myClass = new MyOwnClass( 10, 20 );

$a = $myClass->GetSomeValue(); // this is the old 'a'
$b = $myClass->GetSomeOtherValue(); // this is the old 'b'

but for practical reasons I still want to be able to call

$a = $myClass['a'];
$b = $myClass['b'];

Is something like that possible in php?

  • 写回答

1条回答 默认 最新

  • dsk920417 2015-05-30 10:40
    关注

    Therefore, there is an interface named ArrayAccess. You have to implement it to your class.

    class MyOwnClass implements ArrayAccess {
        private $arr = null;
    
        public function __construct($arr = null) {
            if(is_array($arr))
                $this->arr = $arr;
            else
                $this->arr = [];
        }    
    
        public function offsetExists ($offset) {
            if($this->arr !== null && isset($this->arr[$offset]))
                return true;
            return false;
        }
    
        public function offsetGet ($offset) {
            if($this->arr !== null && isset($this->arr[$offset]))
                return $this->arr[$offset];
            return false;
        }
    
        public function offsetSet ($offset, $value) {
            $this->arr[$offset] = $value;
        }
    
        public function offsetUnset ($offset) {
            unset($this->arr[$offset]);
        }
    }
    

    Use:

    $arr = ["a" => 20, "b" => 30];
    $obj = new MyOwnClass($arr);
    
    $obj->offsetGet("a"); // Gives 20
    $obj->offsetSet("b", 10);
    $obj->offsetGet("b"); // Gives 10
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接