V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lml12377
V2EX  ›  程序员

PHP 的 type hint 如何限制只允许对象参数或返回值?

  •  
  •   lml12377 · 2017-05-20 16:05:26 +08:00 · 1437 次点击
    这是一个创建于 2540 天前的主题,其中的信息可能已经有所发展或是发生改变。

    实现依赖注入容器时,ContainerInterface 的 get 想限制返回值为 object。

    测试代码很简单,试了下参数的限制:

    class Test {}
    
    function testStdClass(\stdClass $obj) {
        var_dump($obj);
    }
    
    testStdClass(new Test());
    

    去网上搜说 \stdClass 在 php 里是大部分类的基类,但测试了并不是这样,除非去主动 extends \stdClass,既然都主动继承了为何不更直接一点,像 yii 那样 ConfigurableInterface/Object/Component,所有组件需要注入到容器的都要继承 Component。

    另外试了 object $obj / Object $obj 也不行。。。

    1 条回复    2017-05-20 17:19:49 +08:00
    Septembers
        1
    Septembers  
       2017-05-20 17:19:49 +08:00 via iPhone
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2313 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 12:31 · PVG 20:31 · LAX 05:31 · JFK 08:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.