php - PHP:阻止在类外创建实例变量
问题描述
在下面给定的 PHP 类中,我知道 $test 将无法从此类外部访问。
class Resource {
private $test;
public function __construct() {
echo "in init";
$test = "new val";
}
}
但是我们将能够定义新的实例变量,如下所示。有什么诀窍可以阻止这种情况吗?
$r = new Resource();
$r->val = "value";
解决方案
例如,使用魔术方法(namly __set
),您可以告诉类“如果此处未设置,请忽略它”;
<?php
class Resource {
private $test;
public function __construct() {
echo "in init";
$this->test = "new val";
}
public function __set($name, $val)
{
// If this variable is in the class, we want to be able to set it
if (isset($this->{$name})
{
$this->{$name} = $val;
}
else
{
// Do nothing, add an error, anything really
}
}
}
$resource = new Resource();
$resource->foo = "bar";
echo $resource->foo; // Will print nothing
供参考,请参阅指南
推荐阅读
- homebrew - 启动了 Grafana,但在 localhost:3000 没有日志或服务器?
- typescript - 对象数组道具装饰器 StencilJS
- php - 提交表单后获取信息
- php - 使用基本身份验证时在 php 中获取用户密码
- c++ - 在 C++ 中异或两个指针
- reactjs - 在graphql中,每次更新“数据”时对“加载”的反应如何?
- javascript - jasmine/sinon 有没有办法存根嵌套函数调用?
- sql - 哪些字符必须转义才能获得合法的 SQLite 字符串文字?
- excel - 复选框(ActiveX 控件)不再起作用
- security - 如何创建 HashiCorp Vault 策略以防止用户破坏机密版本?