目的のために、クラス内に「このクラス」を含む変数/マジックプロパティはありnew
ますか?
が欲しいです:
trait foo {
public function __construct( $x ) {
// ... do stuff ...
}
static function init( $x ) {
return new __THISCLASS__( $x ); // <--- whuzzat?
}
)
class A {
use foo;
}
class B {
use foo;
}
これを行う理由は、関数が実際には複数のクラスで使用されるTraitに含まれているためです。したがって、実行されているクラスを把握して対応するオブジェクトを作成できるようにするための共通コードが必要です。
A::init()
A
オブジェクトとオブジェクトを返す必要がB::init()
ありB
ます。
PHP7.3の実行
このようなことを達成するための最も簡単で読みやすい方法static
は、後期静的バインディングを利用するために使用することだと思います。
例えば:
trait aTrait {
public static function build($x) {
return new static($x);
}
}
class A
{
public function __construct($x) {
$this->x = $x;
}
use aTrait;
}
class B
{
public function __construct($x) {
$this->x = $x * 2;
}
use aTrait;
}
$a = A::build(2);
$b = B::build(2);
var_dump($a);
var_dump($b);
get_called_class()
これは単に便利です。マニュアルの言葉:
get_called_class —「LateStaticBinding」クラス名
これらは常に元々使用されていたクラスを参照しているため、__CLASS__
またはself
ビルダーメソッドには使用しません。後でクラスを拡張すると、メソッドは期待どおりに機能しません。
たとえば、次のようなものです。
trait dangerTrait
{
public static function build($x) {
return new self($x);
}
}
class X
{
use dangerTrait;
public function __construct($x) {
$this->x = $x * 3;
echo "building class ", __CLASS__, "\n";
}
}
class Y extends X {
public function __construct($x) {
$this->x = $x * 4;
echo "building class ", __CLASS__, "\n";
}
}
$x = X::build(2);
$y = Y::build(2);
...出力されます:
building class X
building class X
および両方$x
と$y
はのインスタンスになりますX
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加