简体   繁体   English

PHP通过常量的值访问对象属性

[英]PHP access object property through constant's value

I have a Player class which has properties: $infantry, $vehicles and $air. 我有一个Player类,该类具有以下属性:$ infantry,$ vehicles和$ air。

When battling players, I don't know which property is being used as an array which holds the properties to be used is shuffled to create a random order. 当与玩家作战时,我不知道哪个属性被用作数组,该数组保存了要使用的属性以随机排列。

I try to use this, but it doesn't work. 我尝试使用它,但是它不起作用。 Strangely it doesn't give me empty property error so I assume it's pointing to some property: 奇怪的是,它不会给我空属性错误,因此我认为它指向某些属性:

<?php

$typeOrder = array(_INF_, _VEH_, _AIR_); // _INF_ const = "infantry" etc
$turnOrder = $typeOrder;
shuffle($turnOrder);
for($i = 0; $i < 3; $i++)
{
   $attType = $turnOrder[$i];
   print $p1->$attType;
}

?>

How do I properly access a property with the value held in a constant? 我如何正确地访问具有常量值的属性?

Thanks. 谢谢。

It should work - as long as $p1->infantry etc exist. 只要$p1->infantry等存在,它就应该起作用。 What error does PHP give you exactly? PHP到底给您什么错误?

By the way, have a look at array_rand() . 顺便看看一下array_rand()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM