2016-04-08 2 views
1

を、私は私のクラスのモデルと他のクラスといくつかの問題を持っているので、私は私の問題を説明するために、この単純な例を作った:は静的メソッドでは、現在のクラスからオブジェクトを作成する - PHP

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 

だから私は知りたいです代わりに$v = new person();を書いて、最後に継承されたクラスのオブジェクトを取得します。

答えて

1

late static bindingstaticというキーワードを使用してください。

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

ので、student::getobject()であなたはstudentのインスタンスを取得します。

$bの妥当性を取得するには、$st::$bまたは単にstudent::$bを実行します。

+0

Ahhhhhhhhhhhhhhhh私はこのためにPHPで死ぬんだ、静的およびクラス名との関係が何であるかを、ここでは静的何ん、とにかく、それが働いている、あなたに感謝し、私は5分後に正しいものとして、あなたの答えをマークします、私は今それを行うことはできません:)サイトのルールのために –

関連する問題