When I instantiate a class in PHP, do I get a pointer to an object?

Or is my variable holding the object by itself?

When I say for example:

$obj = new ClassOne();

      

is $ obj a pointer to an object created in memory? Does it only support the memory address for the object? Or does he hold the object himself?

For example, when I say

$obj = new SomeOtherClass();

      

Will the ClassOne object be garbage collected like in JAVA or will it cause a memory leak like in C ++?

+3


source to share


3 answers


In short, the object models in C ++ and Java are slightly different:



  • C ++ has unlimited variables: every object type can arise as an object type, which is variable and shy. In other words, variables can be objects of any type. (But not all va & shy; ri & shy; ables are objects (for example, re & shy; fe & shy; rences)!) In addition, all variables break off, and, therefore, the lifetime of all objects-those-variables is also automatically changes. Only dynamically allocated objects can never be variables, and they can only be manipulated using pointers and references.

  • In Java, if we ignore primitive types, variables are never objects, and objects can never be variables. All objects are always "magically somewhere else" (like "heap GC") and you can only manipulate them with the index pens. In Java, a type variable is T

    always a reference to an actual type object T

    that lives somewhere else. Variables are also limited as in C ++, but the lifetime of all Java objects is undefined and only guaranteed by ex & shy; they go beyond the lifetime of all references to a given object.

    (The situation is different from the built-in types of the "value" type int

    , which can arise as a type of variables and cannot in fact be dynamically allocated.)

  • I think PHP is similar to Java in this regard.

0


source


The documentation says:

PHP treats objects in the same way as references or descriptors, which means that each variable contains a reference to an object, not a copy of the entire object. See "Objects and Links".



Read the documentation. That's why it was written.

+2


source


There are no pointers in PHP. The variable containing the object contains the identifier of the object or a reference to the object. It is a variable that is mostly of type object

with a value 42

(or independently of the internal identifier of the object). It is a value that refers to an object that is stored somewhere in memory. It is not a pointer or memory address. Assigning another object to a variable assigns a different object identifier to the variable, it does not change any memory address or previously assigned object.

+2


source







All Articles