Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP中的超类和子类_Php_Oop - Fatal编程技术网

PHP中的超类和子类

PHP中的超类和子类,php,oop,Php,Oop,考虑以下PHP类代码 class SuperIdea{ . . . static function getById($id){ new SuperIdea(.......); } . . . . } class SubIdea extends SuperIdea{ } 这里我面临的问题是,当我调用SubIdea::getbyId($t);返回的对象是SuperIdea类型,但我希望它是SubIdea类型。有没有方法在不重复SubIdea中的代码的情况下实现它 尝试用new{get_cal

考虑以下PHP类代码

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

class SubIdea extends SuperIdea{
}

这里我面临的问题是,当我调用SubIdea::getbyId($t);返回的对象是SuperIdea类型,但我希望它是SubIdea类型。有没有方法在不重复SubIdea中的代码的情况下实现它

尝试用
new{get_called_class()}()替换
newsuperidea()

我从未测试过这一点,但我看不出它不起作用的原因…

Ivar的答案(基本上,使用get_调用_class())是有效的。请投票/选择他的答案

快速演示:

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

class subcls extends supercls {

}

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

对象(子概念)#1(1){
[“var”]=>
字符串(6)“foobar”
}


PHP>=5.3

值得注意的是,
get_called_class
在PHP5.3中是新的。有没有可以在PHP4中使用的解决方案?
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));