Static Methods in PHP with syntax and examples Inheritance in php
Static methods belong to a class, not instances. They can be called without creating an object.
Syntax:
class ClassName {
public static function staticMethod() {
// code
}
}
Example:
class Math {
public static function add($a, $b) {
return $a + $b;
}
}
echo Math::add(5, 10); // outputs 15
Inheritance in PHP:
Inheritance allows a child class to inherit properties and methods from a parent class.
Syntax:
class ChildClass extends ParentClass {
// code
}
Example:
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sound() {
echo "The animal makes a sound.";
}
}
class Dog extends Animal {
public function sound() {
echo "The dog barks.";
}
}
$dog = new Dog("Max");
echo $dog->name; // outputs "Max"
$dog->sound(); // outputs "The dog barks."
Static Method Inheritance:
Static methods can be inherited and overridden.
Example:
class Animal {
public static function sound() {
echo "The animal makes a sound.";
}
}
class Dog extends Animal {
public static function sound() {
echo "The dog barks.";
}
}
Dog::sound(); // outputs "The dog barks."
Final Methods and Classes:
- final methods cannot be overridden
- final classes cannot be inherited
Example:
class Animal {
final public function sound() {
echo "The animal makes a sound.";
}
}
class Dog extends Animal {
// Cannot override final method
// public function sound() {}
}
Abstract Classes and Methods:
- abstract classes cannot be instantiated
- abstract methods must be implemented in child classes
Example:
abstract class Animal {
abstract public function sound();
}
class Dog extends Animal {
public function sound() {
echo "The dog barks.";
}
}
By understanding static methods and inheritance in PHP, you can create robust, reusable code and establish relationships between classes.