通过变量名访问静态对象属性 [英] Access static object property through variable name
本文介绍了通过变量名访问静态对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道可以使用变量作为名称来访问对象属性/方法
I know its possible to access an object property/method using a variable as its name
例如:
$propName = 'something';
$something = $object->$propName;
是否可以对常量或静态属性执行相同的操作?
Is it possible to do the same w/ constants or static properties?
我试过了:
$constName = 'MY_CONST';
$constName = 'MY_CONST';
MyCLass::{$constName};
和
$obj::{$constName};
但似乎没有任何效果,我在任何地方都找不到.
But nothing seems to work and I couldn't find it anywhere.
推荐答案
使用:Class::$$constName
,这个和普通的变量变量.
Use: Class::$$constName
, this is similar to normal variable variables.
演示:
<?php
class MyClass {
public static $var = 'A';
}
$name = 'var';
echo MyClass::$$name; // echoes 'A'
可以通过 constant
访问常量a> 功能:
Constants can be access with the constant
function:
constant('MyClass::'.$constantName)
这篇关于通过变量名访问静态对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文