Reputation: 319
Is keyword new in php means allocating memory on the heap? ex.
class person {
// properties and methods
}
$p1 = new person();
is there a way to create object in stack in PHP like in c++?
ex.
class person {
// properties and methods
}
//inside in main stack
int main() {
person p1;
Upvotes: 5
Views: 1522
Reputation: 4713
Behind the scenes, when you create an object using the "new" keyword, you're creating a zval. The macros used for creating zvals in the core libraries and extensions allocate memory for zvals, so the answer is yes, creating an object in PHP results in creating an object that's stored on the heap. In fact, all types of PHP variables are zvals behind the scenes (this makes for easy conversions), so they're all actually stored on the heap.
If you want to store data on the stack, you'd be better off using a different language.
Upvotes: 6
Reputation: 6836
The answer is YES.
Also, you are not supposed to control the way PHP controls the memory. That's part of a high level language such as PHP. Please note that C++ is a quite low level language (the language itself does not take into account different OS' you have to write different code for different OS' (You may use libraries, ofc, to do that for you)).
Upvotes: 1