Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

So what really happens when we use 'new' in PHP

So what really happens when someone say 'new' in PHP

I believe in C/Java, when new is called, memory is allocated for each instance variables that are needed for an object? (correct me if i am wrong)

Is this the same with PHP?

like image 297
denniss Avatar asked Jul 29 '10 06:07

denniss


People also ask

What does New keyword do in PHP?

The new keyword is used to create an object from a class.

Why we use $this in PHP?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

What is the correct way of initiating a PHP class?

class ¶ Basic class definitions begin with the keyword class , followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word.

Can you create a class in PHP?

Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword.


2 Answers

When you use $var = new Class

  • a new object is created (memory allocated and initialized);
  • its constructor, if any, is called;
  • the object is put into a list of objects and given a unique id;
  • a new zval container1 is created, this container stores, inter alia, the id of the object;
  • the variable $var is associated with this created zval container.


1Definition of what's a zval container.

like image 88
Artefacto Avatar answered Sep 29 '22 01:09

Artefacto


The easiest way would be to check it for yourself using memory_get_usage()

echo memory_get_usage();
$obj1 = new obj1;
$obj2 = new obj2;
$obj3 = new obj3;
echo memory_get_usage();

Same is the case with PHP.

like image 36
Sarfraz Avatar answered Sep 29 '22 02:09

Sarfraz