Defining a class
Learn to define a class with the class keyword.
Defining a class
A class is a template used to create objects. In PHP a class starts with the class keyword, followed by the class name and a body in curly braces.
Example: class User { }. Here User is the class name; the body is empty for now. The class name must start with a letter or underscore. Defining a class does not run it; it only prepares the template.
Class name and body
Class names must start with a letter or underscore; they cannot start with a digit. PHP is case-sensitive, so User and user are different classes. Names like User, Book or Product that start with an uppercase letter and are singular are a good habit.
The body is the area between the curly braces. We will add properties and methods to it; for now it can be empty. An empty body can be written as { }.
Exercise Define the User class
Define a class named User (leave the body empty for now). After the class, write echo "User class defined" . "\n";.
Show example solution
Define with class User { } then write echo after the class.
Example solution:
<?php
// Define the User class
class User {
}
echo "User class defined" . "\n";
Test yourself
-
Which is a valid class definition?
- User class { }
- class User { }
- function User { }
- new User { }
Show answer
class User { } — Correct. The class keyword, the class name and curly braces form the body.
-
Complete the class definition
____ User { }Show answer
class User { } -
Match the parts of a class
- class
- Keyword
- User
- Class name
- { }
- Body