PHP 5.3 ライブラリを PHP 5.2 で動作するように変換しています。私の邪魔をしている主なものは、のような遅い静的バインディングの使用です。return new static($options);
これを変換するreturn new self($options)
と、同じ結果が得られますか?
new self
とはどう違いnew static
ますか?
PHP 5.3 ライブラリを PHP 5.2 で動作するように変換しています。私の邪魔をしている主なものは、のような遅い静的バインディングの使用です。return new static($options);
これを変換するreturn new self($options)
と、同じ結果が得られますか?
new self
とはどう違いnew static
ますか?
同じ結果が得られますか?
あまり。ただし、PHP 5.2 の回避策はわかりません。
new self
とはどう違いnew static
ますか?
self
new
キーワードが実際に書かれているのと同じクラスを指します。
static
、PHP 5.3の最新の静的バインディングでは、メソッドを呼び出した階層内のクラスを参照します。
次の例では、 はB
から両方のメソッドを継承していますA
。self
呼び出しは、 の最初のメソッドの実装でA
定義されているため、 にバインドされますが、 は呼び出されたクラスにバインドされます ( も参照)。A
static
get_called_class()
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
このコードのメソッドが静的でない場合は、 を使用して 5.2 で回避策を得ることができますget_class($this)
。
class A {
public function create1() {
$class = get_class($this);
return new $class();
}
public function create2() {
return new static();
}
}
class B extends A {
}
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
結果:
string(1) "B"
string(1) "B"