Bird
Raised Fist0
PHPprogramming~10 mins

Object instantiation with new in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Object instantiation with new
Define Class
↓
Call new ClassName()
↓
Allocate Memory for Object
↓
Run Constructor (if any)
↓
Return Object Reference
↓
Assign to Variable
↓
Use Object
This flow shows how PHP creates a new object: it defines the class, calls new, allocates memory, runs the constructor, returns the object, and assigns it to a variable.
Execution Sample
PHP
<?php
class Car {
  public $color;
  function __construct($color) {
    $this->color = $color;
  }
}
$myCar = new Car('red');
echo $myCar->color;
?>
This code creates a Car object with color 'red' and prints the color.
Execution Table
StepActionEvaluationResult
1Define class CarClass Car definedClass Car available
2Call new Car('red')Allocate memory for new objectMemory allocated
3Run __construct('red')$this->color = 'red'Object property color set to 'red'
4Return object referenceObject createdReference to Car object returned
5Assign to variable $myCar$myCar = Car object$myCar holds reference to Car object
6echo $myCar->colorAccess property colorOutput: red
💡 Execution ends after printing the color property of the object.
Variable Tracker
VariableStartAfter Step 5Final
$myCarundefinedCar object with color='red'Car object with color='red'
Key Moments - 3 Insights
Why do we use 'new' to create an object?
Using 'new' tells PHP to allocate memory and run the constructor to create a fresh object, as shown in steps 2 and 3 of the execution table.
What does the constructor __construct do here?
The constructor sets the object's color property to 'red' during instantiation, as seen in step 3 where $this->color is assigned.
Why do we assign the new object to a variable?
Assigning to $myCar stores the reference so we can use the object later, shown in step 5 where $myCar holds the object.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $myCar->color after step 5?
Aundefined
B'red'
Cnull
D'blue'
💡 Hint
Check step 3 where the constructor sets color, and step 5 where $myCar is assigned.
At which step is memory allocated for the new object?
AStep 2
BStep 1
CStep 4
DStep 6
💡 Hint
Look at the action column describing memory allocation.
If we did not assign the new object to $myCar, what would happen?
APHP would throw an error.
BThe constructor would not run.
CThe object would be created but immediately lost.
DThe object would be stored in $myCar automatically.
💡 Hint
Refer to step 5 about assignment and variable tracking.
Concept Snapshot
Object instantiation in PHP:
Use 'new ClassName()' to create an object.
This allocates memory and runs __construct.
Assign the object to a variable to use it.
Access properties with -> operator.
Example: $obj = new ClassName();
Full Transcript
This example shows how PHP creates an object using the new keyword. First, the class Car is defined. Then, new Car('red') is called, which allocates memory for the object and runs the constructor to set the color property to 'red'. The object reference is returned and assigned to the variable $myCar. Finally, echo $myCar->color prints 'red'. This process ensures the object is properly created and ready to use.

Practice

(1/5)
1.

What does the new keyword do in PHP?

easy
A. It deletes an existing object.
B. It defines a new class.
C. It calls a function inside a class.
D. It creates a new instance of a class (an object).

Solution

  1. Step 1: Understand the role of new

    The new keyword is used to create an object from a class blueprint.
  2. Step 2: Differentiate from other keywords

    It does not delete objects, call functions, or define classes; it only creates objects.
  3. Final Answer:

    It creates a new instance of a class (an object). -> Option D
  4. Quick Check:

    new creates objects [OK]
Hint: Remember: new = create object from class [OK]
Common Mistakes:
  • Thinking new deletes objects
  • Confusing new with function calls
  • Believing new defines classes
2.

Which of the following is the correct syntax to create a new object of class Car?

class Car {
  // class body
}

// Create object here
easy
A. $car = new Car();
B. $car = Car();
C. new $car = Car();
D. $car = Car.new();

Solution

  1. Step 1: Recall PHP object creation syntax

    In PHP, to create an object, use $variable = new ClassName();.
  2. 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.
  3. Final Answer:

    $car = new Car(); -> Option A
  4. Quick Check:

    Use new ClassName() to create objects [OK]
Hint: Use $obj = new ClassName(); always [OK]
Common Mistakes:
  • Omitting the new keyword
  • Placing new after variable
  • Using dot notation like other languages
3.

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();
medium
A. Woof! I am Buddy
B. Woof! I am $name
C. Error: Undefined property
D. Woof! I am

Solution

  1. Step 1: Understand constructor usage

    The constructor sets the name property to "Buddy" when the object is created.
  2. Step 2: Analyze the bark method output

    The bark() method returns "Woof! I am " concatenated with the name property, which is "Buddy".
  3. Final Answer:

    Woof! I am Buddy -> Option A
  4. Quick Check:

    Constructor sets name, bark returns it [OK]
Hint: Constructor sets data; methods use it [OK]
Common Mistakes:
  • Ignoring constructor parameters
  • Using variable name instead of property
  • Expecting syntax error due to missing parentheses
4.

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;
medium
A. Property age should be private.
B. Constructor should not have parameters.
C. Missing new keyword when creating the object.
D. Cannot echo object property directly.

Solution

  1. Step 1: Check object instantiation syntax

    The object is created by calling Person(25) without new, which is invalid in PHP.
  2. Step 2: Correct the instantiation

    Use $person = new Person(25); to create the object properly.
  3. Final Answer:

    Missing new keyword when creating the object. -> Option C
  4. Quick Check:

    Always use new to instantiate objects [OK]
Hint: Always use new before class name to create object [OK]
Common Mistakes:
  • Forgetting new keyword
  • Thinking constructor can't have parameters
  • Confusing property visibility with errors
5.

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?

hard
A. $books[] = new Book($data[1], $data[0]);
B. $books[] = new Book($data[0], $data[1]);
C. $books[] = new Book($data);
D. $books[] = Book($data[0], $data[1]);

Solution

  1. Step 1: Understand constructor parameters

    The constructor expects two parameters: title and author, in that order.
  2. Step 2: Match data array to constructor

    $data[0] is title, $data[1] is author, so new Book($data[0], $data[1]) is correct.
  3. Step 3: Add object to array

    Using $books[] = appends the new object to the array.
  4. Final Answer:

    $books[] = new Book($data[0], $data[1]); -> Option B
  5. Quick Check:

    Use new with correct params and append [OK]
Hint: Match constructor params order exactly when using new [OK]
Common Mistakes:
  • Omitting new keyword
  • Passing whole array instead of separate params
  • Swapping title and author order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard