Array object error (solved)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Array object error (solved)

Post 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
Last edited by dimxasnewfrozen on Wed Jun 02, 2010 4:15 pm, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Array object error

Post 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'];
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Array object error

Post 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");
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Re: Array object error (sovled)

Post by dimxasnewfrozen »

Sweet! Thanks.

Both of your methods worked.
Post Reply