Jump to content

PHP OOP beginner


Utherr12

Recommended Posts

Hey, i've just started learning to make objects in php yesterday and wrote this:

class soul{	var $AuraHandler = array(64);	function AddAura($aura)	{		$i = 0;		for($i;$i<=63;$i++)		{			if(isset($this->AuraHandler[$i]))			{				$this->AuraHandler[$i] = $aura;				break;			}			else continue;						}			}}$_soul = new soul();$_soul->name = "Name1";$_soul->AddAura("MECHANIC_IMMUNITY");

I don't know why but it doesn't really work, echoing $_soul->AuraHandler[0] it shows Array[0]

Link to comment
Share on other sites

Arrays in PHP don't work like arrays in C++. When you say "array(64)", you're actually creating an array with its first member's value set to the integer "64".You can append to an array by just using the "[]" syntax, like so:

class soul{ var $AuraHandler = array(); function AddAura($aura) {  $this->AuraHandler[] = $aura; }}$_soul = new soul();$_soul->name = "Name1";$_soul->AddAura("MECHANIC_IMMUNITY");

Arrays can always be appended to - they work a little list lists/vectors/maps in C++ - they are dynamic structures that allocate memory automatically when they need it.

Link to comment
Share on other sites

So this means my array will have the maximum number of elements?well i wanted to check if the AuraHandler array has something in it, and if it has i want to add another value right after it.How do i navigate from the first element to the second if i just use AuraHandler[] ? why can't i use AuraHandler[0] ?A month ago when i started learning PHP i learned that to create an array with a specific number of elements i can use $v = array(x) for x elements.

Link to comment
Share on other sites

The thing is "x" isn't a number of elements in PHP - it's a bunch (or a sequence) of elements. You can have for example:

$v = array(64, 32, 'some string');

If you know the index you're looking for, or which you want to use, you can put it within the "[]". If for example you wanted to place 'some string' at index 0, you can do:

$v[0] = 'some string';

Using "[]" automatically finds the latest free index, and adds up the value there. No need to check up the rest of the elements.

Link to comment
Share on other sites

i have

	var $AuraHandler = array();			function AddAura($aura)	{		$this->AuraHandler[] = $aura;	}$_soul->AddAura("MECHANIC_IMMUNITY");

And echoed $_soul->AuraHandler[0], it turned Array[0].It doesnt work this way, i had to make another function that returns the Aura like this:

	function GetAura($i)	{		return $this->AuraHandler[$i];		}

now it works.

Link to comment
Share on other sites

Let me guess, your echo line looks like:

echo "$_soul->AuraHandler[0]";

It should instead look like this:

echo $_soul->AuraHandler[0];

The quotes are only if you're echoing a string literal.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...