php / phpDoc - @return instance of $this class?

前端 未结 5 1416
温柔的废话
温柔的废话 2021-02-07 16:08

How do I mark a method as \"returns an instance of the current class\" in my phpDoc?

In the following example my IDE (Netbeans) will see that setSomething always returns

5条回答
  •  名媛妹妹
    2021-02-07 16:36

    Here is 3 work around: (These are just work around. classes must not be designed and implemented to sue the behavior of an IDE)

    Option 1: make the method someOtherMethod abstract or empty method in foo class

    class foo implements ifoo {
        protected $_value = null;
    
        /**
         * Set something
         *
         * @param string $value the value
         * @return ifoo
         */
        public function setSomething($value) {
            $this->_value = $value;
            return $this;
        }
    
        // abstract method or create empty method if you want the method to be
        // to be optional 
        abstract function someOtherMethod();
    }
    

    Option 2:

    Override the method setSomething in bar class

    class bar extends foo {
        /**
         *
         * @param  $value
         * @return bar
         */
        public function setSomething($value) {
            return parent::setSomething($value); 
        }
    
        public function someOtherMethod(){}
    }
    

    Option 3: Use interface

    interface ifoo {
        public function someOtherMethod(){}
    }
    
    class foo {
        protected $_value = null;
    
        /**
         * Set something
         *
         * @param string $value the value
         * @return ifoo
         */
        public function setSomething($value) {
            $this->_value = $value;
            return $this;
        }
    }
    
    class bar extends foo implements ifoo {
    
        public function someOtherMethod(){}
    }
    

提交回复
热议问题