Summary - Classes
Build a user class with class, property, method and $this.
Summary - Classes
In this group you learned PHP class basics: defining a class with class, adding a property with public $name, writing a method with function, in-class access with $this and creating an instance with new.
Now you will combine them into a real User class: a property, a method, access with $this and an instance with new, all together. This is the first step of the OOP journey.
All together
In the final task you will write a User class. It will have a $name property and an introduce method. The method will reach the property with $this->name and introduce itself with echo.
Then you will create an instance with new User() and call the method with $user->introduce(). This is the core loop of OOP: define, instantiate, call.
Exercise Complete the User class
Define a class named User. Add the property public $name = "Guest";. Write a method introduce; in the body write echo "I am " . $this->name . "\n";. After the class, create an instance with $user = new User(); and call the method with $user->introduce();.
Show example solution
Define the class, then write $user = new User(); and $user->introduce();.
Example solution:
<?php
// Write the User class and create an instance
class User {
public $name = "Guest";
function introduce() {
echo "I am " . $this->name . "\n";
}
}
$user = new User();
$user->introduce();
Test yourself
-
How do you access the $name property from inside a method?
- $name
- this.name
- $this->name
- self.name
Show answer
$this->name — Correct. $this->name accesses the $name property of the current instance.
-
Complete the instantiation
$user = ____ User(); $user->introduce();Show answer
$user = new User(); $user->introduce(); -
Match the class parts
- class
- Class definition
- public $name
- Property
- function introduce()
- Method
- new User()
- Instantiation