2011-03-09 22 views
2
<?php class gdTemplateDB { 
     [...] 
    function rewrite_dependencies($section, $id) { 
     global $wpdb, $table_prefix; 
     /*var_dump($this); 
     die;*/ 
     **include($this->plugin_path.'code/t2/templates.php');** 
     [...] 
     } 
?> 

我正在挖掘一個稱爲GD星級評級的wordpress插件的代碼。
有兩個「神奇」的事情,我想不通爲什麼:「魔法」「類」

  1. 上面顯然類沒有父母,但是當我的var_dump的$ this指針,它原來是另一個叫類的一個實例GDStarRating和GDStarRating也沒有父母!而且,你知道$ this指針不能被無限重新實例化。所以我不明白爲什麼$這個指針的行爲就像那樣。
  2. 功能rewrite_dependencies靜態從另一個類(gdTemplateDB::rewrite_dependencies,不$instance->rewrite_dependencies)呼籲gdsrAdmFunc叫,那類也沒有與任何GdStarRating父子關係。但它工作得很好。

請讓我知道,什麼可能會導致這些「魔術」的東西?

回答

1

class a{ 
    function aa(){ 
    var_dump($this); 
    } 
} 

class b{ 
    function bb(){ 
    a::aa(); 
    } 
} 

$ob = new b(); 
$ob->bb(); 

這裏a::aa()輸出

object(b)#1 (0) { // $this is instance of b 
} 

這裏$這在課堂上是b類的對象,因爲,

從函數 bbb調用類 a的3210函數 aa

功能bb類別b從類別b的對象調用。

2

出於向後兼容性的原因,PHP允許您將非靜態方法稱爲靜態方法。當以這種方式調用非靜態方法時,它不確定而不是$this。相反,來自其他實例的值會滲透到新方法中。然而

In C: true 
In B: true 
In A: true 

,如果您標記靜態方法作爲這樣,那麼PHP的行爲正確,並沒有定義$this

您可以用下面的代碼複製此:

class A { 
    function foo() { 
    global $c; 
    echo "In A: " . ($this === $c ? 'true' : 'false') . "\n"; 
    } 
} 

class B { 
    function bar() { 
    global $c; 
    echo "In B: " . ($this === $c ? 'true' : 'false') . "\n"; 
    A::foo(); 
    } 
} 

class C { 
    function baz() { 
    global $c; 
    echo "In C: " . ($this === $c ? 'true' : 'false') . "\n"; 
    B::bar(); 
    } 
} 

$c = new C(); 
$c->baz(); 

它打印。在這個例子中,如果聲明A::foo()static function foo(),並B::bar()static function bar(),你看這個:

In C: true 

Notice: Undefined variable: this in test.php on line 13 
In B: false 

Notice: Undefined variable: this in test.php on line 6 
In A: false 
+0

我怎麼給半個點半在回答問題的答案? :) – Ben 2011-03-09 05:15:53

+0

也許我還不夠清楚,但這解釋了兩個問題。 $ this指針不會從類中神奇地繼承。你只是看到另一個類的$ this指針出現在另一個函數中。 – 2011-03-09 05:18:06

+1

啊,觸摸。 +1 – Ben 2011-03-09 22:11:49

1

是否有一些提取函數調用? $ this指針可以被abitrarily使用此功能重新實例:P

extract(array('this' => new stdClass)); 
var_dump($this); // object(stdClass)[1] 
+0

我看不到**提取**,但無論如何,謝謝你,這些信息對我有幫助:D – perfwill 2011-03-12 14:18:57