• 请不要在回答技术问题时复制粘贴 AI 生成的内容
lml12377
V2EX  ›  程序员

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

  •  
  •   lml12377 · May 20, 2017 · 1856 views
    This topic created in 3324 days ago, the information mentioned may be changed or developed.

    实现依赖注入容器时,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 replies    2017-05-20 17:19:49 +08:00
    Septembers
        1
    Septembers  
       May 20, 2017 via iPhone
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2970 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:54 · PVG 18:54 · LAX 03:54 · JFK 06:54
    ♥ Do have faith in what you're doing.