开发者

PHP: Is code like this possible?

I'm trying to have a user-defined list of game-maps. Because I don't know how many maps will be in the array at design time, I'm trying to dynamically create new variables to contain them. Is this even possible? Here's my failed attempt:

<?php
$maplist=array("map1.aamap.xml","map2.aamap.xml"); //edit this list with your maps
$rounds = 3;           开发者_如何学JAVA      //times to play each map
/*======No need to edit below========*/
global $last;  //store the last played map               
class Map
{
    public $difficulty;
    public $played;  //amount of times played
}
foreach($maplist as $i => $element)
{
    $element = $map[$i];
    $map[$i] = new Map();
}
//snipped other code here
$map[$i]->$played = $x++;  //increment the times played counter <-- FAILS HERE
?>

Parser says: Fatal error: Cannot access empty property

Is something like this even feasible in this manner?


There are some errors in your code:

<?php
$maplist=array("map1.aamap.xml","map2.aamap.xml"); //edit this list with your maps
$rounds = 3;                 //times to play each map
/*======No need to edit below========*/
global $last;  //store the last played map               

Since you are on the global scope here, not inside a function, there is no need for global.

class Map
{
    public $difficulty;
    public $played;  //amount of times played
}
foreach($maplist as $i => $element)
{
    $element = $map[$i];

Is some code missing here? You are not using $element within the loop, so this assignment is not needed.

    $map[$i] = new Map();
}
//snipped other code here
$map[$i]->$played = $x++;  //increment the times played counter <-- FAILS HERE

The syntax to access a member variable is $object->variable, not $object->$variable. The latter one will evaluate $variable and use the value as variable name (E.g., if $variable = "foo", this will try to access $object->foo).

Use $map[$i]->played = $x++; instead.


When accessing the properties of a class, you don't want to use the $ in front of the property name itself.

Replace $map[$i]->$played = $x++; with $map[$i]->played = $x++; to solve the Fatal error: Cannot access empty property error.


You could override the magic methods to provide dynamic properties if you wish:

public function __get($name)
{
...
}

public function __set($name, $value)
{
...
}

http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members

Within each of these functions you could store the data in some internal array structure.


You don't have to use the $ when accessing properties of an instance. Simple use $map[$i]->played. Have a look on the OOP basics.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜