普通和魔法 setter 和 getter 之间的区别
我正在为会话变量使用神奇的 getter/setter 类,但我没有看到普通 setter 和 getter 之间有任何区别。
代码:
class session
{
public function __set($name, $value)
{
$_SESSION[$name] = $value;
}
public function __unset($name)
{
unset($_SESSION[$name]);
}
public function __get($name)
{
if(isset($_SESSION[$name]))
{
return $_SESSION[$name];
}
}
}
现在我注意到的第一件事是我必须调用 $session->_unset('var_name') 来删除变量,这没什么“神奇”的。
其次,当我尝试使用 $session->some_var
时,这不起作用。我只能使用 $_SESSION['some_var']
获取会话变量。
我看过 PHP 手册,但功能看起来和我的一样。
我是否做错了什么,或者这些功能真的没有什么神奇之处吗?
I am using a magic getter/setter class for my session variables, but I don't see any difference between normal setters and getters.
The code:
class session
{
public function __set($name, $value)
{
$_SESSION[$name] = $value;
}
public function __unset($name)
{
unset($_SESSION[$name]);
}
public function __get($name)
{
if(isset($_SESSION[$name]))
{
return $_SESSION[$name];
}
}
}
Now the first thing I noticed is that I have to call $session->_unset('var_name')
to remove the variable, nothing 'magical' about that.
Secondly when I try to use $session->some_var
this does not work. I can only get the session variable using $_SESSION['some_var']
.
I have looked at the PHP manual but the functions look the same as mine.
Am I doing something wrong, or is there not really anything magic about these functions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
第一个问题,当你调用
它时应该与调用相同
关于无法使用 __get();什么不起作用?变量设置为什么以及给出什么警告。确保您已设置
error_reporting()
至 E_ALL。检查您是否已调用
session_start
First issue, when you call
It should be the same as calling
Regarding not being able to use __get(); What doesn't work? What does the variable get set to and what warnings are given. Ensure you have set
error_reporting()
to E_ALL.It may also be a good idea to check you have called
session_start
我认为 getter 和 setter 是用于类内的变量?
?
I thought getters and setters were for variables inside the class?
?
打印
好吧,也许不是“神奇”。但按预期工作。
如果这不是您想要的,请详细说明...
prints
Ok, maybe not "magical". But works as intended.
If that's not what you want please elaborate...
这是我到目前为止对魔术函数的理解,
如果我错了请纠正我...
$SESSION 是一个数组 而不是一个对象
因此您可以使用 $session['field'] 而不是 $session->field 来访问它们
magic 函数允许您在任何函数之前使用函数名称 __fnName 作为
fnNameNewField($value);
因此,它将被分成 NewField 作为键,并将被发送到 __fnName 并对此进行操作,
例如:
setNewId($value) 将被发送到 __set(),其中 key= new_id 和参数...
This is my understanding till now about magic function
Please correct me if i am wrong...
$SESSION is an array and not an Object
therefore you can access them using $session['field'] and not $session->field
magic Function allow you to use the function name __fnName before any function as
fnNameNewField($value);
so ,it will be separated into NewField as key and will be sent to __fnName and oprations will be done on this
eg:
setNewId($value) will be sent to __set() with key= new_id and Parameters...