0
0
PHPprogramming~20 mins

Object instantiation with new in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code?
Consider this PHP code that creates a new object and accesses its property. What will it print?
PHP
<?php
class Dog {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}
$dog = new Dog("Buddy");
echo $dog->name;
?>
ABuddy
BDog
CError: Undefined property
DNULL
Attempts:
2 left
💡 Hint
Look at how the constructor sets the property and what is echoed.
Predict Output
intermediate
2:00remaining
What will this PHP code output?
This code creates two objects from the same class. What will be printed?
PHP
<?php
class Counter {
    public static $count = 0;
    public function __construct() {
        self::$count++;
    }
}
$a = new Counter();
$b = new Counter();
echo Counter::$count;
?>
AError: Cannot access static property
B1
C0
D2
Attempts:
2 left
💡 Hint
Static properties are shared across all instances.
🔧 Debug
advanced
2:00remaining
What error does this PHP code produce?
This code tries to create an object but has a mistake. What error will it cause?
PHP
<?php
class Car {
    private $model;
    public function __construct($model) {
        $this->model = $model;
    }
}
$car = new Car();
echo $car->model;
?>
AFatal error: Cannot access private property Car::$model
BNotice: Undefined property: model
CFatal error: Missing argument 1 for Car::__construct()
DNo error, outputs empty string
Attempts:
2 left
💡 Hint
Check the constructor parameters and how the object is created.
📝 Syntax
advanced
2:00remaining
Which option will cause a syntax error in PHP?
Look at these ways to instantiate an object. Which one is NOT valid PHP syntax?
A$obj = new MyClass();
B$obj = new MyClass[];
C$obj = new MyClass;
D$obj = new MyClass(5);
Attempts:
2 left
💡 Hint
Check the use of brackets after the class name.
🚀 Application
expert
3:00remaining
How many objects are created and what is the output?
This code creates objects inside a loop and prints a property. How many objects are created and what is printed?
PHP
<?php
class Item {
    public $id;
    public function __construct($id) {
        $this->id = $id;
    }
}
$items = [];
for ($i = 1; $i <= 3; $i++) {
    $items[] = new Item($i);
}
foreach ($items as $item) {
    echo $item->id . " ";
}
?>
A3 objects created; output: '1 2 3 '
B1 object created; output: '3 '
C3 objects created; output: '3 3 3 '
DError: Cannot use object in array
Attempts:
2 left
💡 Hint
Each loop iteration creates a new object with a different id.