php self() with current object's constructor

£可爱£侵袭症+ 提交于 2019-12-25 05:04:55

问题


What's the proper way to get new self() to use the current instance's constructor? In other words, when I do:

class Foo{
  function create(){
    return new self();
  }
}

Class Bar extends Foo{
}

$b = new Bar();
echo get_class($b->create());

I want to see: Bar instead of: Foo


回答1:


public static function create()
{
    $class = get_called_class();

    return new $class();
}

This should work.

class Foo{
  public static function create()
    {
        $class = get_called_class();

        return new $class();
    }
}

class Bar extends Foo{
}

$a = Foo::create();
$b = Bar::create();

echo get_class($a), PHP_EOL, get_class($b);

Shows:

Foo Bar

UPD:

If you want non-statics, then:

<?php
class Foo{
  public function create()
    {
        $class = get_class($this);

        return new $class();
    }
}

class Bar extends Foo{}

$a = new Bar();
$b = $a->create();

echo get_class($a), PHP_EOL, get_class($b);
?>

Shows:

Bar Bar



回答2:


class Foo{
  function create(){
    $c = get_class($this);
    return new $c();
  }
}

Class Bar extends Foo{
}

$b = new Bar();
echo get_class($b->create());

Store the class type in a temp variable and then return a new instance of it.




回答3:


Class Bar extends Foo {
function create(){
return self;
}}

If you call a function from a child class then it if it will search the nearest parent to call it. This is inheritance.

The idea is to use polymorphism in this situation. Redeclaring a function from child override it's parent's activity. If you want to run it's parent function too then you have to call it like parent::callee();



来源:https://stackoverflow.com/questions/15963547/php-self-with-current-objects-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!