1. js
var obj = {col1: "111", col2: "222"}
console.log(obj.col1) // 固定变量名
console.log(obj['col1'])// 属性访问既可以. 也可以下标[]
console.log(obj['col' + 1]) // 动态拼接属性名(属性名为变量),只能使用[]来处理
2.php
class Obj {
var $col1 = "111";
var $col2 = "222";
}
$obj = new Obj();
echo $obj->col1."\r\n";
for($i = 1; $i <= 2; ++$i) {
echo $obj->{"col$i"}."\r\n";
}
// php的静态变量
class Test{
static $name;
public static function testParam() {
self::$name = "hello world";
$a = "name";
echo self::${$a};
}
}
Test::testParam();
3. c/c++
使用双#来处理,宏方法中使用很多。
4. java
// 使用反射来处理, 不管是方法名还是属性名皆可拼接
Class trendClass = curTrend.getClass();
Method getMethod = trendClass.getMethod("getSpace" + i);
Method setMethod = trendClass.getMethod("setSpace" + i, Integer.class);
本文介绍了不同编程语言中如何实现动态属性访问的方法,包括JavaScript中的obj['col'+1]、PHP中的$obj->{'col'.$i}
4860

被折叠的 条评论
为什么被折叠?



