Type hinting for properties in PHP 7?

前端 未结 4 1697
庸人自扰
庸人自扰 2020-12-10 10:15

Does php 7 support type hinting for class properties?

I mean, not just for setters/getters but for the property itself.

Something like:

         


        
4条回答
  •  隐瞒了意图╮
    2020-12-10 10:32

    You can use setter

    class Bar {
        public $val;
    }
    
    class Foo {
        /**
         *
         * @var Bar
         */
        private $bar;
    
        /**
         * @return Bar
         */
        public function getBar()
        {
            return $this->bar;
        }
    
        /**
         * @param Bar $bar
         */
        public function setBar(Bar $bar)
        {
            $this->bar = $bar;
        }
    
    }
    
    $fooInstance = new Foo();
    // $fooInstance->bar = new NotBar(); //Error
    $fooInstance->setBar($fooInstance);
    

    Output:

    TypeError: Argument 1 passed to Foo::setBar() must be an instance of Bar, instance of Foo given, called in ...
    

提交回复
热议问题