2011-09-06 76 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