Firefox https://www.codecademy.com/learn/learn-php/modules/classes-and-objec...
Cheatsheets / Learn PHP
Classes and Objects in PHP
PHP extends keyword
In PHP, to de�ne a class that inherits from another, we
use the keyword extends : // Dog class inherits from Pet class.
class Dog extends Pet {
class ChildClass extends function bark() {
ParentClass {
return "woof";
}
}
}
The newly de�ned class can access members with
public and protected visibility from the base class, but
cannot access private members.
The newly de�ned class can also rede�ne or override
class members.
PHP Constructor Method
A constructor method is one of several magic methods
provided by PHP. This method is automatically called // constructor with no arguments:
when an object is instantiated. A constructor method is class Person {
de�ned with the special method name __construct . The public $favorite_color;
constructor can be used to initialize an object’s function __construct() {
properties.
$this->favorite_color = "blue";
}
}
// constructor with arguments:
class Person {
public $favorite_color;
function __construct($color) {
$this->favorite_color = $color;
}
}
1 of 2 5/11/2022, 1:09 PM
Firefox https://www.codecademy.com/learn/learn-php/modules/classes-and-objec...
PHP class
In PHP, classes are de�ned using the class keyword.
Functions de�ned within a class become methods and // Test class
variables within the class are considered properties. class Test {
There are three levels of visibility for class members: public $color = "blue";
protected $shape = "sphere";
public (default) - accessible from outside of the
private $quantity = 10;
class
public static $number = 42;
protected - only accessible within the class or its public static function returnHello() {
descendants
return "Hello";
private - only accessible within the de�ning class }
}
Members can be de�ned to be static:
Static members are accessed using the Scope
// instantiate new object
Resolution Operator ( :: ) $object = new Test();
Classes are instantiated into objects using the new // only color can be accessed from the
keyword. Members of an object are accessed using the instance
Object Operator ( -> ). echo $object->color; # Works
echo $object->shape; # Fails
echo $object->quantity; # Fails
echo $object->number; # Fails
// we use the static class to access
number
echo Test::$number;
2 of 2 5/11/2022, 1:09 PM