6

How can I declare a list of objects in php as a private instance variable?

In Java the declaration would look something like this private ArrayList<Object> ls and the constructor would have this ls = new ArrayList<Object>();

Thanks

2 Answers 2

5

PHP allocates memory dynamically and what's more, it doesn't care what sort of object you store in your array.

If you want to declare your array before you use it something along these lines would work:

var $myArray = array();

Then you can store any object you like in your variable $myArray. Many people find this a strange concept to grasp after working in a strict language like java.

Sign up to request clarification or add additional context in comments.

4 Comments

What is the difference between var $myArray = array() and $array = array()
there is no difference, that's only name of that variable, you can use whatever you want :) it's like ls in your question
I meant whether I use 'var' or not before the variable.
@user1114 it's deprecated way to declare class variables (used in PHP 4), in PHP 5 you should use public/private..
1

you can declare it in class like

private $array = array();

and append objects (or anything) to that array like

$array[] = some object

1 Comment

You can also use it associatively, by saying $array['key'] = value;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.