简体   繁体   中英

PHP access object property through constant's value

I have a Player class which has properties: $infantry, $vehicles and $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. What error does PHP give you exactly?

By the way, have a look at array_rand() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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