2011-09-06 66 views
0

可能重複的動作=:
Operator Overloading in PHPPHP覆蓋將實例變量

我想創建一個庫,允許在PHP類型安全的變量。我想要做以下事情:

class int extends typeClass{ 
    protected $value; 

public function __construct($value){ 
    // Check if the parameter is a integer. 
    if(! is_int($value)){ 
     throw new typeIntegerException('This isn\t an Integer.'); 
    } 
    $this->value = $value; 
} 

// Returns the $value instead of the int class 
public function __get(){ 
    return $this->value; 
} 

// Sets $value instead of the class 
public function __set($value){ 
    if(! is_int($value)){ 
     throw new typeIntegerException('This isn\t an Integer.'); 
    } 
    $this->value = $value; 
} 
} 

$test = new int(5); 
$test = "3"; 

其中$ test =「3」;我想在這裏調用__set或其他方法,而不是使$ test「3」。有可能這樣做嗎?

由於提前,

問候, 鮑勃

回答

0

你最接近的選項是Spl Types庫。問題是它被認爲是實驗性的,可能會被棄用。恩惠在於它完全符合你所要做的。

+0

那麼獲得我想要的唯一方法就是使用實驗課?但是如果我把它做對了,這是可能的,因爲Spl類型與我想創建的相同。那麼他們是如何做到的呢?有沒有辦法我可以看到那裏的課程的源代碼?或者它是在另一個語言,然後PHP?仍然非常感謝您的答案btw ^^ – Bob

+0

他們在C中完成了它,並將其添加爲擴展。我想你可以分叉代碼並在必要時自己維護它。 – cwallenpoole

+0

好的信息^^ – Bob