0

私はこのシナリオを持っています:

class A extends B {
   public function test() {
       parent::test();
   }
}

class B extends someCompletelyOtherClass {
   public function test() {
       //what is the type of $this here?
   } 
}

機能テストのクラス B の $this の型は何ですか? AまたはB?試してみたらA、Bだと思ってた?なんでアなの?

ありがとう!

4

3 に答える 3

2

私は PHP の専門家ではありませんが、これは理にかなっていると思います。メソッドがクラス B で定義されている場合でも、$this は型 A のインスタンス化されたオブジェクトを指す必要があります。

クラス B のインスタンスを作成し、そのテスト メソッドを直接呼び出す場合、$this はタイプ B のオブジェクトを指す必要があります。

于 2012-06-04T12:04:47.030 に答える
0

test()問題は、静的に、つまりクラス コンテキストで呼び出していることです。非静的関数を静的に呼び出すのはエラーです (残念ながら、PHP はこれを強制しません)。

$this->test()ではなく、を使用する必要がありますparent::test()

于 2012-06-04T11:57:38.940 に答える
-1

PHPでは、キーワード「$this」はクラスの自己参照として使用され、クラスの関数と変数を呼び出して使用するために使用できます。そしてここに例があります:

class ClassOne
{
    // this is a property of this class
    public $propertyOne;

    // When the ClassOne is instantiated, the first method called is
    // its constructor, which also is a method of the class
    public function __construct($argumentOne)
    {
        // this key word used here to assign
        // the argument to the class
        $this->propertyOne = $argumentOne;
    }

    // this is a method of the class
    function methodOne()
    {
        //this keyword also used here to use  the value of variable $var1
        return 'Method one print value for its '
             . ' property $propertyOne: ' . $this->propertyOne;
    }
}

また、parent::test() を呼び出すと、実際には CLASS B に関連付けられたテスト関数を呼び出します。これは、静的に呼び出しているためです。$this->test() と呼んでみると、B ではなく A が得られるはずです。

于 2012-06-04T11:57:58.440 に答える