2012-07-25 32 views
4
class A{ 
    const FOO = 1; 
} 

class B extends A{ 

    const FOO = 5; 

    function foo(){ 
    print self::FOO; 
    print static::FOO; 
    } 
} 

$b = new B; 
$b->foo(); 

它在兩種情況下打印5個。靜態關鍵字對常量有影響嗎?

所以在常量上使用靜態和自我沒有區別?

+0

我得到'分析錯誤:語法錯誤,意外的T_STATIC'。你有錯誤報告嗎? – 2012-07-25 19:54:06

+0

是的,我有 – Alex 2012-07-25 19:55:04

+0

@WesleyMurch顯然,使用'static'作爲範圍只適用於PHP 5.3及以上版本。你有更低版本的PHP嗎?這可能是錯誤的根源。 – Palladium 2012-07-25 19:55:11

回答

3

Late Static Binding有上下文是一個區別。

考慮以下代碼:

<?php 

class A { 
    const FOO = 1; 

    function bar() { 
     print self::FOO; 
     print "\n"; 
     print static::FOO; 
    } 
} 

class B extends A { 
    const FOO = 5; 
} 

$b = new B; 
$b->bar(); // 1 5 

如果你運行該代碼時,輸​​出將是:

1 
5 

當引用self::FOO1值打印(即使bar()被稱爲上類B,但是當使用static關鍵字時,後期靜態綁定已生效,並且它參考B之後的FOO常數當使用static關鍵字時,使用r。

這與PHP 5.3及更高版本相關。

+0

tx。我想我誤解了後期的靜態綁定。看起來它跟從父類中做孩子班的東西有關 – Alex 2012-07-25 21:07:31

+0

是的,起初它很混亂,但基本上你是在正確的軌道上。在父類中使用'static'允許這些父類在運行時從派生類訪問屬性,常量和方法(如果調用是由派生對象進行的)。雖然'self :: FOO'是指'A'類的'FOO',因爲'bar'在'A'中定義,'static :: FOO'可以指'B'類的'FOO',因爲我們最終調用'即使在'A'中定義了'bar()',也可以從'B'使用bar()。 – drew010 2012-07-25 21:31:07

2

在你的例子中沒有足夠的東西來看看有什麼不同。但是,如果您有:

class Foo 
{ 
    protected static $FooBar = 'Foo'; 

    public function FooBar() 
    { 
    echo "static::\$FooBar = " . static::$FooBar . PHP_EOL; 
    echo "self::\$FooBar = " . self::$FooBar . PHP_EOL; 
    } 
} 

class Bar extends Foo 
{ 
    protected static $FooBar = 'Bar'; 
} 

$bar = new Bar(); 
$bar->FooBar(); 

你會看到不同(示波器和實例被解析[繼承與基地])

self, parent and static keywords

1

是的,有區別。在您的示例代碼中,selfstatic都是指相同的const FOO聲明。

用戶「drew010」發送的示例顯示了差異。