Object instantiation with new in PHP - Time & Space Complexity
When we create new objects in PHP using new, it takes some time to set up each object.
We want to know how the time needed grows as we create more objects.
Analyze the time complexity of the following code snippet.
class Item {
public function __construct() {
// Some setup code
}
}
$items = [];
for ($i = 0; $i < $n; $i++) {
$items[] = new Item();
}
This code creates $n new objects of the Item class and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new
Itemobject inside the loop. - How many times: Exactly
$ntimes, once per loop iteration.
Each new object takes a similar amount of time to create, so total time grows as we add more objects.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The time grows directly in proportion to the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Creating objects inside a loop is instant and does not affect performance."
[OK] Correct: Each object creation takes some time, so doing it many times adds up and affects total time.
Understanding how object creation time grows helps you write efficient code and explain your reasoning clearly in interviews.
"What if the constructor of Item did some heavy work like reading a file? How would the time complexity change?"
Practice
What does the new keyword do in PHP?
Solution
Step 1: Understand the role of
Thenewnewkeyword is used to create an object from a class blueprint.Step 2: Differentiate from other keywords
It does not delete objects, call functions, or define classes; it only creates objects.Final Answer:
It creates a new instance of a class (an object). -> Option DQuick Check:
newcreates objects [OK]
- Thinking new deletes objects
- Confusing new with function calls
- Believing new defines classes
Which of the following is the correct syntax to create a new object of class Car?
class Car {
// class body
}
// Create object here
Solution
Step 1: Recall PHP object creation syntax
In PHP, to create an object, use$variable = new ClassName();.Step 2: Check each option
$car = new Car(); matches the correct syntax. The other options use invalid syntax: new before variable assignment, omitting the new keyword, or using dot notation.Final Answer:
$car = new Car(); -> Option AQuick Check:
Usenew ClassName()to create objects [OK]
- Omitting the new keyword
- Placing new after variable
- Using dot notation like other languages
What will be the output of the following PHP code?
class Dog {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function bark() {
return "Woof! I am " . $this->name;
}
}
$dog = new Dog("Buddy");
echo $dog->bark();
Solution
Step 1: Understand constructor usage
The constructor sets thenameproperty to "Buddy" when the object is created.Step 2: Analyze the bark method output
Thebark()method returns "Woof! I am " concatenated with thenameproperty, which is "Buddy".Final Answer:
Woof! I am Buddy -> Option AQuick Check:
Constructor sets name, bark returns it [OK]
- Ignoring constructor parameters
- Using variable name instead of property
- Expecting syntax error due to missing parentheses
Identify the error in this PHP code snippet:
class Person {
public $age;
public function __construct($age) {
$this->age = $age;
}
}
$person = Person(25);
echo $person->age;
Solution
Step 1: Check object instantiation syntax
The object is created by callingPerson(25)withoutnew, which is invalid in PHP.Step 2: Correct the instantiation
Use$person = new Person(25);to create the object properly.Final Answer:
Missingnewkeyword when creating the object. -> Option CQuick Check:
Always usenewto instantiate objects [OK]
- Forgetting new keyword
- Thinking constructor can't have parameters
- Confusing property visibility with errors
Given this class:
class Book {
public $title;
public $author;
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
}
// Create an array of books with titles and authors
$booksData = [
['1984', 'George Orwell'],
['Brave New World', 'Aldous Huxley'],
['Fahrenheit 451', 'Ray Bradbury']
];
// Fill this array with Book objects
$books = [];
foreach ($booksData as $data) {
// Fill here
}
Which line correctly creates and adds a new Book object to $books inside the loop?
Solution
Step 1: Understand constructor parameters
The constructor expects two parameters: title and author, in that order.Step 2: Match data array to constructor
$data[0] is title, $data[1] is author, sonew Book($data[0], $data[1])is correct.Step 3: Add object to array
Using$books[] =appends the new object to the array.Final Answer:
$books[] = new Book($data[0], $data[1]); -> Option BQuick Check:
Use new with correct params and append [OK]
- Omitting new keyword
- Passing whole array instead of separate params
- Swapping title and author order
Ready to prove it?
Pass the test and this pattern moves unknown
