程式設計裡的綁定時間是指軟體裡的兩個数据實體或是兩個程式碼實體何時建立關聯(綁定)。綁定時間可能是在程式開始執行前,也可能是在開始執行之後。早綁定(early binding)也稱為靜態綁定(static bindind),是指在程式執行前就有的綁定,在運行時無法修改。(late binding)也稱為動態綁定(dynamic binding),是在運行時才進行的綁定。綁定時間可以適用於任何一種綁定方式,包括名字、記憶體(例如透過malloc)以及型別(例如針對)。
例子
以下的Java程式中有早綁定,也有遲綁定。方法是早綁定,綁定於第三行宣告的程式碼。對的呼叫是遲綁定,因為List是介面,因此list一定是指它的某個子类型。list可能是參考LinkedList、ArrayList,或是List的其他子类型。add參考的方式一直要到執行時才會知道。
:
import java.util.List;
public void foo(List list) {
list.add("bar");
}
相關
遲靜態綁定
遲靜態綁定是一種介於早綁定和遲綁定之間的綁定。考慮以下的PHP範例:
class A
{
public static $word = "hello";
public static function hello() { print self::$word; }
}
class B extends A
{
public static $word = "bye";
}
B::hello();
在此例中,PHP編譯器會將A::hello()的self綁定到類別A,因此,呼叫B::hello()會產生字串"hello"。若self::$word的語義是基於遲靜態綁定,則其結果會是"bye"。
從PHP 5.3版起,開始支援遲靜態綁定。若將以上程式中的self::$word改為static::$word,如以下範例所示,其中static只會在運行時綁定,呼叫B::hello()的結果也會是"bye":
class A
{
public static $word = "hello";
public static function hello() { print static::$word; }
}
class B extends A
{
public static $word = "bye";
}
B::hello();
相關條目
评论 (0)