I have been trying to access a public array inside a class, but it is freaking out on me. Should this be able to work?

$TestArra = array('Hello', ' ', 'World');

class Test
{
	function Test()
	{
		$this->Display();
	}
	
	function Display()
	{
		foreach($TestArray as $value)
		{
			echo $value;
		}
	}
}

shouldn't that display "Hello World" on the page? instead i get this error:

Warning: Invalid argument supplied for foreach() in C:\xampplite\htdocs\xampp\Links\test.php on line

Maybe I just don't understand something. Any help would be great.

Thanks.

p.s. Also I can't create an array for some reason either. I tried $a = array('a'); and $a[0] = 'a'; neither would seem to work in the class.

Recommended Answers

All 5 Replies

<?
$objtest = new Test(array('Hello', ' ', 'World'));
$objtest->echoArrayA1();
$objtest->echoArrayA2();

class Test
{
	var $TestArray = array();
	
	function Test($inputArray)
	{
		$this->setTestArray($inputArray);
		$this->Display();
	}
	
	function Display()
	{
		foreach($this->TestArray as $value)
		{
			echo $value;
		}
	}
	
	function setTestArray($inputArray)
	{
		if(is_array($inputArray))
		{
			$this->TestArray = $inputArray;
		}
	}
	
	function echoArrayA1()
	{
		$a = array('a');
		foreach($a as $value)
		{
			echo "<br />" . $value;
		}
	}
	
	function echoArrayA2()
	{
		$a[0] = 'b';
		foreach($a as $value)
		{
			echo "<br />" . $value;
		}
	}
}
?>

Any Questions?

So you have to pass it an array? you can't just grab a global one?

So you have to pass it an array? you can't just grab a global one?

You have to declare it as global in the function, view the last function in the class

<?
$globalTestArray = array('Hello', ' ', 'World', '2');
$objtest = new Test(array('Hello', ' ', 'World'));
$objtest->echoArrayA1();
$objtest->echoArrayA2();

class Test
{
	var $TestArray = array();
	
	function Test($inputArray)
	{
		$this->setTestArray($inputArray);
		$this->Display();
		$this->echoGlobalTestArray();
	}
	
	function Display()
	{
		foreach($this->TestArray as $value)
		{
			echo $value;
		}
	}
	
	function setTestArray($inputArray)
	{
		if(is_array($inputArray))
		{
			$this->TestArray = $inputArray;
		}
	}
	
	function echoArrayA1()
	{
		$a = array('a');
		foreach($a as $value)
		{
			echo "<br />" . $value;
		}
	}
	
	function echoArrayA2()
	{
		$a[0] = 'b';
		foreach($a as $value)
		{
			echo "<br />" . $value;
		}
	}
	
	function echoGlobalTestArray()
	{
		global $globalTestArray;
		echo "<br />";
		foreach($globalTestArray as $value)
		{
			echo $value;
		}
		echo "<br />";
	}
}
?>
commented: This helped me to figure out the answer +4

ok didn't notice the global. Thanks works now.

On to the next problem.

No problem :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.