0
0
PHPprogramming~10 mins

Methods and $this keyword in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to call the method inside the class using $this.

PHP
<?php
class Car {
    public function start() {
        echo "Car started";
    }
    public function run() {
        $this->[1]();
    }
}
$car = new Car();
$car->run();
?>
Drag options to blanks, or click blank then click option'
Astop
Brun
Cstart
Ddrive
Attempts:
3 left
💡 Hint
Common Mistakes
Using the method name without $this->
Calling a method that does not exist
2fill in blank
medium

Complete the code to access the property inside the method using $this.

PHP
<?php
class Person {
    public $name = "Alice";
    public function greet() {
        echo "Hello, " . $this->[1];
    }
}
$person = new Person();
$person->greet();
?>
Drag options to blanks, or click blank then click option'
Aname
Bhello
Cgreet
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access property without $this->
Using a wrong property name
3fill in blank
hard

Fix the error in the method to correctly return the object's property using $this.

PHP
<?php
class Book {
    public $title = "PHP Basics";
    public function getTitle() {
        return [1]->title;
    }
}
$book = new Book();
echo $book->getTitle();
?>
Drag options to blanks, or click blank then click option'
Athis
B$this
C$self
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'this' without $ sign
Using 'self' which refers to the class, not the object instance
4fill in blank
hard

Fill both blanks to create a method that sets the object's property using $this.

PHP
<?php
class Laptop {
    public $brand;
    public function setBrand([1]) {
        $this->[2] = $brand;
    }
}
$laptop = new Laptop();
$laptop->setBrand("Dell");
echo $laptop->brand;
?>
Drag options to blanks, or click blank then click option'
Astring $brand
Bbrand
Cmodel
Dprice
Attempts:
3 left
💡 Hint
Common Mistakes
Not using a parameter in the method
Assigning to a wrong property name
5fill in blank
hard

Fill all three blanks to create a method that updates and returns the object's property using $this.

PHP
<?php
class Phone {
    public $color = "Black";
    public function changeColor([1]) {
        $this->[2] = $newColor;
        return $this->[3];
    }
}
$phone = new Phone();
echo $phone->changeColor("Red");
?>
Drag options to blanks, or click blank then click option'
Astring $newColor
Bcolor
DnewColor
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter name
Returning a variable instead of the property