【问题标题】:php overwrite the = action of an instanced variable [duplicate]php覆盖实例变量的=动作[重复]
【发布时间】:2011-11-11 12:58:33
【问题描述】:

可能重复:
Operator Overloading in PHP

我正在尝试创建一个允许在 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"。有可能吗?

提前致谢,

您好, 鲍勃

【问题讨论】:

    标签: php oop class overwrite type-safety


    【解决方案1】:

    您最接近的选择是Spl Types 库。问题是它被认为是实验性的,可能会被弃用。好处是它完全符合您的要求。

    【讨论】:

    • 那么获得我想要的东西的唯一方法是使用实​​验课?但如果我做对了,这是可能的,因为 Spl 类型与我想要创建的相同。那么他们当时是怎么做到的呢?有没有办法可以看到那里类的源代码?或者是其他语言,然后是php?仍然非常感谢您的回答 ^^
    • 他们在 C 中完成并添加它作为扩展。我想您可以分叉代码并在必要时自行维护。
    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2013-02-22
    相关资源
    最近更新 更多