PHP Class
A class is a blueprint for creating objects. It defines the properties (variables) and methods (functions) that its objects will have. If you are new to OOP, first read PHP OOP Introduction.
Syntax of a PHP class
A class starts with the class keyword, then the class name, then curly braces that contain the properties and methods.
<?php
class ClassName {
// properties
// methods
}
?>
- By convention a class name starts with a capital letter, like
StudentorOrderItem. - Properties are declared with a visibility keyword:
public,protectedorprivate. - Inside a method, use
$thisto reach the properties of the current object.
Example: class with properties and a method
<?php
class Student {
// Properties
public $name;
public $course;
// Constructor: runs when the object is created
public function __construct($name, $course) {
$this->name = $name;
$this->course = $course;
}
// Method
public function display() {
return $this->name . " is learning " . $this->course;
}
}
$s1 = new Student("Robin", "PHP");
$s2 = new Student("Jenny", "MySQL");
echo $s1->display() . "<br>";
echo $s2->display();
?>
Output:
Tutorials Class - Output Window
Robin is learning PHP
Jenny is learning MySQL
We made two objects from one class. Each object keeps its own values. See What is a constructor in PHP? for more on __construct().
Visibility: public, protected, private
| Keyword | Can be used from |
|---|---|
| public | Anywhere |
| protected | Inside the class and its child classes |
| private | Inside the same class only |
Read the full explanation with an example in public, private and protected.
Class constants
A constant belongs to the class and its value can not change. It is declared with const and used with ::.
<?php
class Circle {
const PI = 3.14159;
public function area($radius) {
return self::PI * $radius * $radius;
}
}
echo Circle::PI . "<br>";
$c = new Circle();
echo $c->area(2);
?>
Output:
Tutorials Class - Output Window
3.14159
12.56636
Note:
In old PHP code you may see var $name; to declare a property. It still works, but use public in new code.
Summary
- A class is a blueprint, objects are created from it with
new. - A class has properties and methods.
$thispoints to the current object,self::points to the class.- Use visibility keywords to control access.
Next chapter: PHP Objects.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |