Type hinting for properties in PHP 7?

前端 未结 4 1688
庸人自扰
庸人自扰 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:43

    Edit for PHP 7.4 :

    Since PHP 7.4 you can type attributes (Documentation / Wiki) which means you can do :

        class Foo
    {
        protected ?Bar $bar;
        public int $id;
        ...
    }
    

    According to wiki, all acceptable values are :

    • bool, int, float, string, array, object
    • iterable
    • self, parent
    • any class or interface name
    • ?type // where "type" may be any of the above

    PHP < 7.4

    It is actually not possible and you only have 4 ways to actually simulate it :

    • Default values
    • Decorators in comment blocks
    • Default values in constructor
    • Getters and setters

    I combined all of them here

    class Foo
    {
        /**
         * @var Bar
         */
        protected $bar = null;
    
        /** 
        * Foo constructor
        * @param Bar $bar
        **/
        public function __construct(Bar $bar = null){
            $this->bar = $bar;
        }
        
        /**
        * @return Bar
        */
        public function getBar() : ?Bar{
            return $this->bar;
        }
    
        /**
        * @param Bar $bar
        */
        public function setBar(Bar $bar) {
            $this->bar = $bar;
        }
    }
    

    Note that you actually can type the return as ?Bar since php 7.1 (nullable) because it could be null (not available in php7.0.)

    You also can type the return as void since php7.1

提交回复
热议问题