php - 如何在 PHP 中修改类的静态属性?
问题描述
考虑以下代码:
class MyClass
{
public static $test = 'foo';
public function example()
{
return Self::$test;
}
}
// What I'm trying to do
MyClass->$test = 'bar';
$test = new MyClass();
echo $test->example(); // Should return `bar` instead of `foo`.
这在 PHP 中是否可行?
解决方案
您走在正确的轨道上,您只需要以 Class::$test 的形式访问变量
class MyClass
{
public static $test = 'foo';
public function example()
{
return Self::$test;
}
}
MyClass::$test = 'bar';
$test = new MyClass();
echo $test->example(); // returns bar
推荐阅读
- rust - 如何实现一个委托给 HashMap::values() 的迭代器
- python - 有没有办法为机器学习模型中的每个预测给出一个理由
- c++ - 在 ubuntu 18.04 上安装 Nvidia Cuda 10.2 + CuDNN 7.5 +OpenCV 4.2.0 后的链接问题
- c# - 为群聊发起 DeepLink url 调用
- html - 一个一个地显示 ul 元素
- c# - 使用 Serilog 通过电子邮件发送在程序结束时创建的日志文件
- python - 当python中的相似元素时如何有效地组合列表中的元组
- python - PyTest : 在运行时动态生成测试名称
- css - 使用 Nextjs 应用程序中的样式组件更改活动引导导航链接的颜色。(打字稿)
- c++ - 在 C++ 子类中使用继承的属性和“结构”