Khalil Bz
Khalil Bz

Reputation: 607

Create an object from the current class in a static method - PHP

I have some problems with my class Model and other classes so I made this simple example to explain my problem :

class person{

  public static $a = "welcome";

  public function __construct(){
                               }

  public static function getobject()
  {
      $v = new person();
      return $v;
  }

}

class student extends person{

  public static $b = "World";

}

$st = student:getobject();//this will return person object but I want student object

echo $st->$b; // There is an error here because the object is not student

So I want to know what to write instead $v = new person(); to get the object of the last inherited class.

Upvotes: 1

Views: 1719

Answers (1)

Federkun
Federkun

Reputation: 36924

Use the late static binding's static keyword.

public static function getobject()
{
    $v = new static();
    return $v;
}

So, with student::getobject() you get an instance of student.

To retrieve the static (but why?) $b propriety, you can do $st::$b, or simply student::$b.

Upvotes: 5

Related Questions