PHP 接口实际上如何改变类的行为
P粉289775043
P粉289775043 2023-09-02 23:49:28
[PHP讨论组]

根据 PHP 文档,

对象接口允许您创建指定类必须实现哪些方法的代码,而无需定义这些方法的实现方式。

因此,接口就像一个具有预定义方法的类,仍然需要使用 -> 符号来访问

但是,ArrayAccess 接口提供对对象作为数组的访问。可以使用 $object->property$object["property"]

访问对象

我无法理解 ArrayAccess 如何使更改对象语法成为可能。我编写了一段代码来尝试复制 ArrayAccess 方法仅一个的效果,但它抛出错误

// Using the PHP ArrayAccess Interface

namespace A {
    
    class myclass implements \ArrayAccess {
        public function offsetExists($offset) { return true; }
        public function offsetGet($offset) {
            // changed behaviour
            return $this->{$offset} ?? null;
        }
        public function offsetSet($offset, $value) {}
        public function offsetUnset($offset) {}
    }

    $myclass = new myclass();
    $myclass->access = 'Interface';
    echo $myclass['access']; // "Interface"

};

//Trying to implement my own ArrayAccess Interface

namespace B {
    
    interface MyArrayAccess {
        public function offsetGet($offset);
    }
    
    class myclass implements MyArrayAccess {
        public function offsetGet($offset) {
            // change behaviour
            return $this->{$offset} ?? null;
        }
    }
    
    $myclass = new myclass();
    $myclass->access = 'Interface';
    echo $myclass['access']; // Fatal error: Uncaught Error: Cannot use object of type B\myclass as array

}

请帮我正确解释一下。谢谢

P粉289775043
P粉289775043

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号