PHP OOP Essentials: Classes, Objects, and Core Concepts
PHP Object Basics
Defining and Using Instances
- Define Instance
$student1 = new Student;
- Set Value to Property
$student1->firstName = "ex";
- Calling Object Function
$student1->getName();
- Refer to the Instance (inside the class)
$this->name;
Visibility Modifiers
- public
- Accessed from anywhere. Example:
public $property_name;
(orvar $property_name;
for older PHP versions) - protected
- Accessed only from this class and its subclasses. Example:
protected $property_name;
- private
- Accessed from inside the class only. Example:
private $property_name;
Inheritance Basics
- Define Subclass
class Child extends Parent {}
Static Members and Constants
- Static Property
public static $property_name;
- Class Constant
public const CONSTANT_NAME_UPPERCASE = value;
- Calling Static/Constant Property (Inside Class)
self::$property_name;
orself::CONSTANT_NAME_UPPERCASE;
- Calling Static/Constant Property (Outside Class)
ClassName::$property_name;
orClassName::CONSTANT_NAME_UPPERCASE;
- Inheritance Behavior
- A static property is a shared variable between a class and its subclasses. Any change in one affects the others.
- Calling Parent Class Static Method
parent::method_name();
- Late Static Binding
- Use
static::$property_name;
orstatic::method_name()
to refer to the called class at runtime, allowing static inheritance to work as expected, rather than being bound only to the class whereself
was used.
Magic Methods in PHP
Magic methods are special methods that override PHP’s default actions when certain operations are performed on an object.
- They must be declared as public.
- Their names start with a double underscore (
__
).
- __construct() (Constructor)
- Called automatically when a new instance of the class is created.
Example:public function __construct($arg1 = 'Default value', $arg2, ...) {}
orpublic function __construct($args = []) {}
- __destruct() (Destructor)
- Called automatically when the last reference to an object is destroyed (e.g., script end or using
unset()
).
Example:public function __destruct() {}
Useunset($instance);
to explicitly trigger the destruction if it’s the last reference. - __clone() (Clone)
- Called when an object is cloned using the
clone
keyword (e.g.,$instance2 = clone $instance1;
). Copies instance data.
Example:public function __clone() {}
- Autoloading (via
spl_autoload_register
) - While not a magic method itself, autoloading handles cases when PHP encounters an unknown class name. You define a function to load the class file and register it.
Define function:function my_autoloader($className) { /* include file based on $className */ }
Register function:spl_autoload_register('my_autoloader');
Property Overloading
PHP allows for dynamic properties (properties not explicitly declared in the class definition):
- Accessing an undefined property results in a notice (or error, depending on PHP version/settings).
- Assigning a value to an undefined property creates it dynamically.
Example:
class Student {}
$s1 = new Student;
echo $s1->name; // Notice: Undefined property
$s1->name = 'Waleed'; // Dynamically creates and sets the 'name' property
echo $s1->name; // Outputs: Waleed
Note: Relying heavily on dynamic properties can make code harder to understand and maintain. Use magic methods like __get()
and __set()
for controlled overloading.
Comparing Objects
- Comparison (
==
) - Returns
true
if the two object instances are of the same class and have the same properties and values (shallow comparison). - Identity (
===
) - Returns
true
only if both variables point to the exact same instance in memory.
Useful PHP OOP Functions
Class Functions
get_declared_classes()
- Returns an array of the names of all declared classes in the current script.
class_exists($className)
- Checks if a class has been defined. Returns
true
if the class named by the string$className
exists.
Instance Functions
get_class($object)
- Returns the name of the class of which the
$object
is an instance. is_a($object, $className)
- Checks if the
$object
is an instance of the class$className
or has$className
as one of its parents. Returnstrue
if it is.
Property Functions
get_class_vars($className)
- Returns an associative array of the default properties (including visibility) defined in the class
$className
. get_object_vars($object)
- Returns an associative array of the properties (and their values) accessible from the current scope for the given
$object
. property_exists($mixed, $propertyName)
- Checks if an object (
$mixed
can be an object instance or class name string) has a specific property, even if the value isnull
. Returnstrue
if the property$propertyName
exists.
Method Functions
get_class_methods($mixed)
- Returns an array of method names defined for a given class (
$mixed
can be an object instance or class name string). method_exists($mixed, $methodName)
- Checks if a class method exists in a given object or class (
$mixed
can be an object instance or class name string). Returnstrue
if the method$methodName
exists.
Inheritance Functions
get_parent_class($mixed)
- Returns the name of the parent class for an object or class (
$mixed
can be an object instance or class name string). Returnsfalse
if the object/class has no parent. is_subclass_of($mixed, $className)
- Checks if the object/class (
$mixed
) is a subclass of the given$className
. Returnstrue
if it is. class_parents($mixed)
- Returns an array containing the names of all parent classes of the given object or class (
$mixed
).
Static Binding Functions
get_class()
- Inside a method, returns the name of the class the method belongs to (where it was defined), regardless of inheritance.
get_called_class()
- Inside a static method, returns the name of the class that was actually called at runtime (useful for late static binding).