This is the way属性是用C#语言定义的。
在C#中与PHP不同,类属性不是简单变量,当您设置或获取它们的值时,会调用访问器函数。因此,您可以锁定属性,使其在初始化后不被更改。在PHP中似乎没有函数名称后跟括号,你不能调用这样的值。 PHP中是否有类似的概念?
答案 0 :(得分:1)
尚未,但在未来的PHP版本中“可能”
RFC:https://wiki.php.net/rfc/propertygetsetsyntax
Magic _ get / _set和“overloading”,是各种代码异味的情况。
答案 1 :(得分:0)
我不明白你的意思。
但是,如果您正在讨论getter和setter,您可以简单地将var声明为private并创建一个公共方法来获取值。
private $lol;
public getlol(){
return $this->lol;
}
但如果您正在谈论污染物,您需要尝试一下:
define("MAXSIZE", 100);
答案 2 :(得分:0)
使用__get and __set magic methods在PHP中获取和设置方法是可能的(尽管实现与C#不同)
class A {
protected $test_int;
function __construct() {
$this->test_int = 2;
}
function __get($prop) {
if ($prop == 'test_int') {
echo 'test_int get method<br>';
return $this->test_int;
}
}
function __set($prop, $val) {
if ($prop == 'test_int') {
echo 'test_int set method<br>';
//$this->test_int = $val;
}
}
}
$obj = new A();
$obj->test_int = 3; //Will echo 'test_int set method'
echo $obj->test_int; //Will echo 'test_int get method' and then the value of test_int.
如果您想“锁定”某个属性的值,只需执行以下操作:
function __set($prop, $val) {
if ($prop == 'test_int') {
//Do nothing
}
}