Jump to content

[SOLVED] Can't access array in a class


percent20

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/111538-solved-cant-access-array-in-a-class/
Share on other sites

To stop dancing around the point, your array example fails for one of two possible reasons, depending on what you're trying to do:

 

1. If your array is supposed to be part of the class, it fails because the array is not declared as a property of the class.

2. If your array is not supposed to be part of the class, it fails because you're not passing it to the object as a method argument.

 

Example of using the array as a property of the class:

<?php
   class Test
   {
      private $testArray = array('Hello', ' ', 'World'); //best to keep it private, as you shouldn't give the outside world direct access to class properties

      public function __construct()
      {
         $this->display();
      }

      public function display()
      {
         foreach($this->testArray as $value)
         {
            echo $value;
         }
      }
   }

   $myObj = new Test();
?>

 

Example of passing the array as an argument:

<?php
   $testArray = array('Hello', ' ', 'World');

   class Test
   {
      public function __construct($array)
      {
         $this->display($array);
      }

      public function display($array)
      {
         foreach($array as $value)
         {
            echo $value;
         }
      }
   }

   $myObj = new Test($testArray);
?>

 

Note: the examples I've written use PHP 5 syntax.

Finally figured out how to get it working.  Since it needs to be independent and global I had to use the global keyword inside the class to pull it into scope.  I didn't know about the global until yesterday. Until I can convince others here to do non-public global variables for config it has to be done this way :(

 

Thanks for the help.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.