Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the method name without $this->
Calling a method that does not exist
✗ Incorrect
Inside a class, to call another method, you use $this->methodName(). Here, $this->start() calls the start method.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to access property without $this->
Using a wrong property name
✗ Incorrect
Inside the method, $this->name accesses the property 'name' of the current object.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'this' without $ sign
Using 'self' which refers to the class, not the object instance
✗ Incorrect
In PHP, $this refers to the current object inside methods. So, return $this->title; is correct.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using a parameter in the method
Assigning to a wrong property name
✗ Incorrect
The method parameter should be 'string $brand' to accept a string argument. Inside the method, $this->brand sets the object's property.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter name
Returning a variable instead of the property
✗ Incorrect
The method parameter is 'string $newColor'. Inside the method, $this->color is updated and returned.