class Foo
{
public $var ;
function __construct($value)
{
$this->var = $value ;
}
}
$myFoo = new Foo('hello');
echo $myFoo->var . '<br>' ; // output : hello
// Question : how can I prevent another programer from accidentaly doing the following
$myFoo = 4 ;
echo $myFoo ; // output : 4
我的问题在评论//问题:...
我希望我的同事能够为$ myFoo分配值仅使用$ myFoo-&gt; var(或类Foo中可用的任何公共mutators)
谢谢
编辑: 对于声称不可能的用户而言,SPL_Types PECL扩展能够实现(在某种程度上)看到例如http://php.net/manual/en/class.splint.php或http://blog.felixdv.com/2008/01/09/spl_types-in-php-and-strong-typing/
答案 0 :(得分:2)
你不能用任何弱类型的语言来做这件事。如果您有将此变量作为参数的函数,则可以在PHP中使用类型提示,但是否则您无法阻止人们重新分配其变量。
即使对于强类型语言,这也是如此。如果程序员创建了一个类的两个实例,则没有机制阻止它们将不同的实例分配给相同类型的变量。
这种情况发生的唯一方法是程序员明确使用常量而不是变量(例如在Java中使用final
之类的东西,或{{ 1}}在Scala中,等等,但无论如何,你无法用任何语言控制它。
答案 1 :(得分:0)
您无法阻止更改类中的类型,但如果您将其设置为protected或private,然后添加setVariable()方法(其中Variable是您的变量名称),则可以控制输入。类似的东西:
class myClass {
protected $integer = 0;
public function setInteger($new_value)
{
if (!is_int($new_value)) {
throw new RuntimeException('Cannot assign non-integer value to myClass::$integer');
}
$this->integer = $new_value;
}
public function getInteger()
{
return $this->integer;
}
}
// Now, outside of the class, the $integer property can only be changed using setInteger()
$class = new myClass;
$class->setInteger('dog'); // Uncaught Runtime exception ...
$class->setInteger(5);
echo $class->getInteger(); // 5
该函数的替代版本将接受字符串编号并将其转换为整数:
public function setInteger($new_value)
{
if (!is_numeric($new_value)) {
throw new RuntimeException('Cannot assign non-integer value to myClass::$integer');
}
$this->integer = (int) $new_value;
}
$class->setInteger('5'); // 5