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

为君一笑 提交于 2019-12-23 20:15:35

问题


Or, does my variable hold the object itself?

When I say for example:

$obj = new ClassOne();

is the $obj a pointer to the object created in the memory? Does it hold only the memory address to the object? Or does it hold the object itself?

For example when I say,

$obj = new SomeOtherClass();

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


回答1:


Briefly, the object models in C++ and Java are a bit different:

  • C++ has unconstrained variables: Every object type can occur as the type of an object that is a vari­able. In other words, variables can be objects of any type. (But not all va­ri­ables are objects (e.g. re­fe­rences)!) Moreover, all variables are scoped, and thus the lifetime of all objects-that-are-variables is also scoped automatically. Only dynamically-allocated objects can never be variables, and they can only be handled via pointers and references.

  • In Java, if we ignore the primitive types, variables are never objects, and objects can never be variables. All objects are always "magically somewhere else" (e.g. "the GC heap"), and you can only ever handle them through pointer-like handles. In Java, a variable of type T is always a reference to the actual object of type T, which lives somewhere else. Variables are also scoped, like in C++, but the lifetime of all Java objects is indeterminate, and only guaranteed to ex­tend beyond the lifetime of all references to a given object.

    (The situation is different for built-in, "value"-type types like int, which can occur as the type of variables, and in fact cannot be allocated dynamically.)

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




回答2:


There are no pointers in PHP. A variable that holds an object holds an object identifier or object reference. That's a variable basically of the type object with the value 42 (or whatever the internal object identifier is). It is a value that is referencing an object, which is stored somewhere in memory. It's not a pointer or memory address though. Assigning another object to the variable assigns another object identifier to the variable, it does not alter any memory address or the previously assigned object.




回答3:


The documentation says:

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References.

Read the documentation. That's why it has been written.



来源:https://stackoverflow.com/questions/14413496/when-i-instantiate-a-class-in-php-do-i-get-a-pointer-to-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!