How to create an array of objects?

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
vbnandu86
Forum Newbie
Posts: 3
Joined: Mon Apr 14, 2008 3:23 am

How to create an array of objects?

Post by vbnandu86 »

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


consider the following :-

Code: Select all

 
<?php
class Person
{
var $name;
var $salary;
}
 
$p = array()
$p[0] = new Person;
$p[0]->name= "jax";
$p[0]->salary= 1000;
 print_r($p[0]);
 ?>
 
 
This gives me an error as "Parse error: syntax error, unexpected T_VARIABLE in C:\webs\test\object.php on line 9"
Can anyone tell me how to create an array of objects of the class Person??


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.
m4rv5
Forum Newbie
Posts: 13
Joined: Fri Apr 11, 2008 12:49 am

Re: How to create an array of objects?

Post by m4rv5 »

vbnandu86 wrote:consider the following :-

Code: Select all

 
<?php
class Person
{
var $name;
var $salary;
}
 
$p = array()
$p[0] = new Person;
$p[0]->name= "jax";
$p[0]->salary= 1000;
 print_r($p[0]);
 ?>
 
 
This gives me an error as "Parse error: syntax error, unexpected T_VARIABLE in C:\webs\test\object.php on line 9"
Can anyone tell me how to create an array of objects of the class Person??

Onl line: 9 you forgot to add semi-colon ;
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: How to create an array of objects?

Post by onion2k »

By putting the required ; at the end of line 9.

EDIT: Beaten to it. :)

Couple of other things though..

1. Read the error message. It tells you what's wrong with your script. If it says there was a parse error that means you've got some syntax wrong somewhere.

2. It's a good idea to have methods in your object to get and set variables rather than setting them from 'outside'.
vbnandu86
Forum Newbie
Posts: 3
Joined: Mon Apr 14, 2008 3:23 am

Re: How to create an array of objects?

Post by vbnandu86 »

Actually I had done other forms of somersaults to get this . I had created
This simple example to post on the forum.....
Surprised that this is correct....
Thanks any way fr ur attention though!!! :-P
Post Reply