php self() with current object's constructor

2019-08-29 08:00发布

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

3条回答
何必那么认真
2楼-- · 2019-08-29 08:10
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
查看更多
爷、活的狠高调
3楼-- · 2019-08-29 08:25
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.

查看更多
男人必须洒脱
4楼-- · 2019-08-29 08:25
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();

查看更多
登录 后发表回答