2012-01-12 8 views
4

以下の例が実際にどのように動作しているか、どのように動的に何かを行うことができますか? call_user_funcまたはcall_user_func_arrayを使用しても、これは発生しません。PHP 5.3でインスタンスメソッドを使用すると奇妙な結果が発生する

<?php 
class Person 
{ 
    public $name = "George"; 

    public function say_hi() 
    { 
      return ExtraMethods::hi(); 
    } 
} 

class ExtraMethods 
{ 
    public function hi() 
    { 
      return "Hi, ".$this->name; 
    } 
} 

$george = new Person(); 
echo $george->say_hi(); 
?> 

これは、となるはずである:インスタンスメソッドhiだけでなく、静的に(これはPHPで発生する可能性があることに驚いていない)と呼ばれることができる理由

Hi, George 

は疑問に思うが、私は $thisを使用することができる午前理由 manualから

答えて

4

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

したがって、2番目の部分によれば、設計通りです。しかし、実際に存在するオブジェクトインスタンスを使用していることに注意してください(つまり、public $name = "SomethingElse";ExtraMethodsに追加すると、結果はまだHi, Georgeになります)。静的メソッドを呼び出す

は、適切なコーディングではありませんが、PHPはあなたを許し、そして唯一の厳格なエラー問題:もちろん

"Strict Standards: Non-static method ExtraMethods::hi() should not be called statically, assuming $this from incompatible context in ..." 

は、この例では、単にオブジェクトを引数として渡すと、はるかに明確になります好ましい。

+0

ああ、完璧です。私はこれが何らかのレガシーサポートのために行われたと思いますか? – tamagokun

+0

まあ、PHP4のレガシーかもしれませんが、 'static'キーワード/静的メソッドは利用できませんでした。 – Wrikken

関連する問題