Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an array of objects in php

Tags:

php

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

like image 669
user1114 Avatar asked Jan 06 '12 14:01

user1114


People also ask

How do you declare and initialize an array in PHP?

Syntax to create an empty array: At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting. In other words, the initialization of new array is faster, use syntax var first = [] rather while using syntax var first = new Array().

How do you declare an object variable in PHP?

The object is declared to use the properties of a class. The object variable is declared by using the new keyword followed by the class name. Multiple object variables can be declared for a class.

What is array of object with example?

Each variable or object in an array is called an element. Unlike stricter languages, such as Java, you can store a mixture of data types in a single array. For example, you could have array with the following four elements: an integer, a window object, a string and a button object.

What is PHP array with example?

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.


2 Answers

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.

like image 109
James Ravenscroft Avatar answered Sep 30 '22 09:09

James Ravenscroft


you can declare it in class like

private $array = array();

and append objects (or anything) to that array like

$array[] = some object
like image 40
boobiq Avatar answered Sep 30 '22 09:09

boobiq