2012-10-03 25 views
5

可能性の重複:
Get class name from extended classは、構築クラスのクラス名を取得

と仮定私は、次があります。

class Foo 
{ 
    public $name; 

    public __construct() 
    { 
    $this->name = __CLASS__; 
    } 
} 

class Bar extends Foo 
{ 
} 

class FooBar extends Foo 
{ 
} 

$bar = new Bar(); 
echo $bar->name; // will output 'Foo', but I want 'Bar' 

$foobar = new FooBar(); 
echo $foobar->name; // will output 'Foo', but I want 'FooBar' 

が名を取得する方法はあります構造化クラスの名前を拡張クラスに設定せずにFooクラスの名前を設定しますか?

注:私はFooから派生した多くのクラスを持っています。派生クラスごとに名前を設定すると、多くのコーディングが必要になります。

+0

何 'get_class()'とすべての他の関連するfctnsについてはどうですか? – Havelock

答えて

0

これは非常に簡単ですget_class()

$fooBar = new FooBar(); 
echo get_class($fooBar); //will output FooBar 
3

クラス名を取得するには、PHPの関数でビルドがあります:ちょうどget_called_classを使用します。

$this->name = get_called_class(); 

これは、導入遅延静的バインディング機能の一部ですが、 PHP 5.3でメソッドが定義されているクラスではなく、呼び出されたクラスを参照します。

+2

'__construct'は本当に静的メソッドではないので(それは' $ this'へのアクセス権を持っています)、 – lanzz

関連する問題