Challenge - 5 Problems
Master of Methods and $this
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method using $this keyword
What is the output of this PHP code?
PHP
<?php class Car { public $color = 'red'; public function getColor() { return $this->color; } } $car = new Car(); echo $car->getColor(); ?>
Attempts:
2 left
💡 Hint
Remember $this refers to the current object instance.
✗ Incorrect
The method getColor() returns the $color property of the current object using $this->color. Since $color is set to 'red', the output is 'red'.
❓ Predict Output
intermediate2:00remaining
Effect of missing $this in method
What error or output does this PHP code produce?
PHP
<?php class Person { public $name = 'Alice'; public function sayName() { return name; } } $p = new Person(); echo $p->sayName(); ?>
Attempts:
2 left
💡 Hint
Check how properties are accessed inside methods.
✗ Incorrect
Inside the method, name without $this-> is treated as a constant. Since no constant named 'name' exists, PHP throws an error.
🔧 Debug
advanced2:30remaining
Why does this method not update the property?
Consider this PHP code. Why does the
setAge method not change the $age property of the object?PHP
<?php class User { public $age = 20; public function setAge($age) { $age = $age; } } $user = new User(); $user->setAge(30); echo $user->age; ?>
Attempts:
2 left
💡 Hint
Look at how the assignment is done inside the method.
✗ Incorrect
The method assigns the parameter $age to itself, which does nothing. To update the object's property, it should use $this->age = $age;.
📝 Syntax
advanced2:00remaining
Identify the syntax error in method using $this
Which option contains the correct syntax to return the
$name property inside a method?PHP
<?php class Animal { public $name = 'Dog'; public function getName() { // return statement here } } ?>
Attempts:
2 left
💡 Hint
Remember the correct syntax to access properties with $this.
✗ Incorrect
To access an object property inside a method, use $this->propertyName. Other options have syntax errors or incorrect variable usage.
🚀 Application
expert3:00remaining
Predict the output of chained method calls using $this
What is the output of this PHP code?
PHP
<?php class Builder { private $text = ''; public function addHello() { $this->text .= 'Hello '; return $this; } public function addWorld() { $this->text .= 'World!'; return $this; } public function getText() { return $this->text; } } $b = new Builder(); echo $b->addHello()->addWorld()->getText(); ?>
Attempts:
2 left
💡 Hint
Check how methods return $this to allow chaining.
✗ Incorrect
Each method appends text and returns $this, allowing chaining. The final getText() returns the full string 'Hello World!'.