Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is keyword new in php means allocating memory on the heap?

Tags:

php

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;
like image 372
user1628256 Avatar asked Aug 27 '12 21:08

user1628256


People also ask

Does new keyword allocate memory in heap?

new keywordThe new operator is an operator which denotes a request for memory allocation on the Heap. If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Does new allocate on heap?

C++ uses the new operator to allocate memory on the heap.

How do I allocate memory to heap?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

Which keyword is used to allocate memory for a newly created object address memory store new?

In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static. In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new().


1 Answers

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.

like image 182
AdamJonR Avatar answered Sep 22 '22 22:09

AdamJonR