php self() with current object's constructor

2019-08-29 07:58发布

问题:

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();