开发者

Superclass and Subclasses in PHP

开发者 https://www.devze.com 2023-01-04 07:25 出处:网络
Consider 开发者_如何学Gothe following PHP class code class SuperIdea{ . . . static function getById($id){new SuperIdea(.......); }

Consider 开发者_如何学Gothe following PHP class code

class SuperIdea{
.
.
.
static function getById($id){  new SuperIdea(.......); } 
.
.
.
.
}

class SubIdea extends SuperIdea{
}

The problem I face here is that when I call SubIdea::getbyId($t); the object returned is of type SuperIdea but I would like it to be of SubIdea.Is there any way to achieve it without repeating code in SubIdea?


Try replacing new SuperIdea() with new {get_called_class()}();

I've never tested this, but I see no reason why it shouldn't work...


Ivar's answer (basically, to use get_called_class()) works. Please upvote/select his answer.

Quick demo:

<?PHP
class supercls {
  static function foo(){
         $class = get_called_class();
         echo $class ."\n";
  }
}

class subcls extends supercls {

}

supercls::foo();
subcls::foo();


class SuperIdea {
    public $var;
    function __construct($var){
       $this->var = $var;
    }
    static function getById($id){  return new static('foobar'); } 
}

class SubIdea extends SuperIdea{}
var_dump(SubIdea::getById(0));

object(SubIdea)#1 (1) { ["var"]=> string(6) "foobar" }

PHP >= 5.3

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号