0
0
PHPprogramming~20 mins

Methods and $this keyword in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Methods and $this
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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();
?>
AError: Undefined property
BCar
Cnull
Dred
Attempts:
2 left
💡 Hint
Remember $this refers to the current object instance.
Predict Output
intermediate
2: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();
?>
AError: Undefined constant 'name'
BAlice
Cnull
DEmpty string
Attempts:
2 left
💡 Hint
Check how properties are accessed inside methods.
🔧 Debug
advanced
2: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;
?>
ABecause the method is static and cannot access instance properties.
BBecause $age property is private and cannot be changed.
CBecause the method assigns the parameter to itself, not to the property using $this.
DBecause the property $age is not declared in the class.
Attempts:
2 left
💡 Hint
Look at how the assignment is done inside the method.
📝 Syntax
advanced
2: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
    }
}
?>
Areturn $this->name;
Breturn this->$name;
Creturn $this.name;
Dreturn $name;
Attempts:
2 left
💡 Hint
Remember the correct syntax to access properties with $this.
🚀 Application
expert
3: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();
?>
AError: Cannot chain methods
BHello World!
CWorld!
DHello
Attempts:
2 left
💡 Hint
Check how methods return $this to allow chaining.