Page 1 of 1

Array object error (solved)

Posted: Wed Jun 02, 2010 3:40 pm
by dimxasnewfrozen
I have a very simple class that i'd like to return an array.

privilege.class.php

Code: Select all

class privilege {

	public function __construct(){	
	}
	
	function p($app) {
                // run SQL to get privileges for $app
                // hard coding the privileges for now
		$type = array("Read"=> "R", "Write"=> "W", "Update"=> "U",  "Delete"=> "D");
		return $type;
	}
	
}
main.php

Code: Select all

$privilege = new privileges();
$privilege->p(APP_NAME);
// this is how I'd like to use the array items
echo $privilege->type['read'];
echo $privilege->type['write'];
echo $privilege->type['update'];
echo $privilege->type['delete'];
I'm getting an error:
Undefined property: privileges::$type

Re: Array object error

Posted: Wed Jun 02, 2010 3:55 pm
by requinix
Variables created in a method are not created for the whole class too.

The best design decision (as far as I can tell) would be to use the return value and not to stick the array into the class.

Code: Select all

$privilege = new  privileges();
$type = $privilege->p(APP_NAME);

echo $type['read'];
echo $type['write'];
echo $type['update'];
echo $type['delete'];

Re: Array object error

Posted: Wed Jun 02, 2010 4:09 pm
by AbraCadaver
To do it the way you showed, you would do this:

Code: Select all

function p($app) {
   $this->type = array("Read"=> "R", "Write"=> "W", "Update"=> "U",  "Delete"=> "D");
}
If you wanted to set it for use as a property and return it for whatever reason, then this:

Code: Select all

function p($app) {
   return $this->type = array("Read"=> "R", "Write"=> "W", "Update"=> "U",  "Delete"=> "D");
}

Re: Array object error (sovled)

Posted: Wed Jun 02, 2010 4:15 pm
by dimxasnewfrozen
Sweet! Thanks.

Both of your methods worked.