Cheatsheets / Learn PHP: Objects and Classes
PHP Objects and Classes
PHP extends keyword
In PHP, to define a class that inherits from another, we // Dog class inherits from Pet class.
use the keyword extends :
class Dog extends Pet {
class ChildClass extends ParentClass function bark() {
} return "woof";
}
}
The newly defined class can access members with
public and protected visibility from the base class, but
cannot access private members.
The newly defined class can also redefine or override
class members.
PHP Constructor Method
A constructor method is one of several magic methods // constructor with no arguments:
provided by PHP. This method is automatically called
class Person {
when an object is instantiated. A constructor method is
defined with the special method name __construct . public $favorite_color;
The 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;
}
}
PHP class
In PHP, classes are defined using the class keyword. // Test class
Functions defined within a class become methods and
class Test {
variables within the class are considered properties.
There are three levels of visibility for class members: public $color = "blue";
public (default) - accessible from outside of the
protected $shape = "sphere";
class
protected - only accessible within the class or private $quantity = 10;
its descendants public static $number = 42;
private - only accessible within the defining public static function returnHello() {
class
return "Hello";
Members can be defined to be static:
Static members are accessed using the Scope }
Resolution Operator ( :: ) }
Classes are instantiated into objects using the new
keyword. Members of an object are accessed using the
// instantiate new object
Object Operator ( -> ).
$object = new Test();
// only color can be accessed from the
instance
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;
Save Print Share