[英]How to create a php getter and setter in a javascript way
Please is it possible to create getters and setters in a JavaScript way in php.请是否可以在 php 中以 JavaScript 方式创建 getter 和 setter。 For example:
例如:
JavaScript JavaScript
function test(){
var clr = "";
Object.defineProperty(this, "color", {
set:function(val){
val=="red"?clr=val:val="others";
},
get:function(){
return clr;
}
});
}
Now setting现在设置
var testObj = new test();
testObj.color = "red";
And getting并得到
var testObj = new test();
var color = testObj.color;
Instead of this in php而不是 php
$testObj = new test();
$testObj->setColor("color"); //Setter
$testObj->setColor(); //Getter
But this in php但这在 php
$testObj = new test();
$testObj->setColor = "red";//Setter
$testObj->setColor;//Getter
Which the value would be proccessed before being assigned.在分配之前将处理哪个值。 Also i would like to know the name for the JavaScript way creating getters and setters.
另外我想知道创建 getter 和 setter 的 JavaScript 方式的名称。 Thanks.
谢谢。
Haven't used PHP in a while, so forgive me if the syntax is slightly off, but you can use the __set
and __get
magic methods :有一段时间没有使用 PHP 了,如果语法稍有偏差,请见谅,但您可以使用
__set
和__get
魔术方法:
private $props = [];
public function __set($property, $value) {
switch($property) {
case 'color':
$this->props['color'] = $value == 'red' ? $value : 'others';
break;
}
}
public function __get($property) {
switch($property) {
case 'color':
return $this->props['color'];
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.