TYPE HINTING ON OBJECTS
Let’s see with an image how it is possible to do type hinting to the summary method of the corso class.
THE STATISTICS CLASS
When we talked about functions, we also studied the type hinting scalar, the scalar values in PHP are booleans, integers floats and strings. Regarding the summarize method by returning a string, it would be appropriate to do type hinting as shown in the figure above. Since PHP version five we have type hinting on classes. Let’s create a file Statistics.php inside the lib folder. In this case, the constructor does not receive a scalar value but an object of type course.
THE CHILD FRONTEND CLASS
With the same procedure we create in the file index.php an instance of the class Frontend.php which we remind you is a subclass of Course.php. A child class is something completely related to the parent class; therefore, passing the child class, the type hinting is still respected. The child class is something that extends and inherits the characteristics of the Corso superclass; so, if we think about it it is not a very different thing logically. The figure on the side shows the var_dump of this class.
PROPERTIES AND STATIC METHODS
The properties and methods used so far are instance members, so they can be accessed with the $this keyword , which we remember is a reference to the instance. Sometimes, however, it might be useful to have properties and methods that are not specific to a single instance but belong to the class itself. To create static properties and methods we use the keyword static. The important thing to understand is that if we are inside a static method we are not in the concept of instances, they are methods that belong to the class. So we can’t use the keyword $this to access a property. However, we can access static properties with the keyword self which refers to the class itself . Let’s start by defining a static property in the Corso.php file.
ACCESS PROPERTIES AND STATIC METHODS FROM THE INDEX CLASS
To access properties and methods that have been defined with the keyword static you use the class name followed by the scoope resolution operator :: and the name of the property or method.
ACCESS PROPERTIES AND STATIC METHODS FROM SUB-CLASSES
Let’s move the info () method defined in the Course class to the Frontend e subclass let’s see if it is possible to access the $ platform property defined in Corso.php. Let’s go to the index class and invoke the info () method of the Frontend class. The echo statement shows that the property defined in the parent class can be accessed. Let’s now define the same static property in the Frontend class:
public static string $platform = “Platform Y (of Frontend)“;
Let’s move the info () method back into the Corso.php class. If from index.php we invoke Frontend::info() we access the $platform property defined in Course.php again. If we want to access the property $platform defined in Frontend by the Corso.php class we use the keyword static. There are many possible cases, it would not make sense to analyze them all, they would only lead to confusion.
CONSTANT PROPERTIES
Even within the classes we can define constants, that is, values that cannot be changed. Constants are accessible through the class and not through the instance like static properties and methods. The difference is that properties declared as static can be changed, while constants cannot.
FINAL METHODS AND CLASSES
We have seen that a child class can override (override) a method of the parent class. The child class may need to specialize methods. If a parent class wants to prevent one of its methods from being overridden, the keyword final. With the keyword final set in the method summary() the Backend and Frontend daughter classes will not be able to redefine that method. If we designate a class as final it means that the class cannot be inherited.
ABSTRACT CLASSES
An abstract class must be declared with the keyword abstract before the keyword class. Such classes cannot be instantiated but only inherited. What we can do inside an abstract class is force its subclasses to implement one or more methods. An abstract class typically defines some methods, while others leave the implementation in its subclasses. The figure on the side shows how to declare an abstract method that must necessarily be implemented in the child classes.
INTERFACES
Interfaces are tools similar to abstract classes, if in abstract classes we can implement some methods in interfaces this is not possible. To declare an interface we use the keyword interface.
The Course class that uses the interfaces will have to implement public methods with the same signature as the methods declared in the interfaces. PHP classes can inherit from a single class however, they can implement multiple interfaces.
I TRAIT
Within a trait we can define properties and methods that will be useful to the classes that will use it. Using traits is like copying and pasting properties and methods within the trait and pasting them into the classes that use it. Within a trait we can also use static methods and abstract methods.
SAMPLE CODE
FURTHER INFORMATION
In PHP, abstract classes are classes that cannot be instantiated directly, but provide a framework for other classes.
These classes serve as a base for other classes, forcing derived classes to implement some methods defined in the abstract class.
The abstract keyword is used to declare an abstract class and the abstract methods within it.
Main features of abstract classes in PHP:
1. Cannot be instantiated: It is not possible to create a direct instance of an abstract class.
The abstract class is meant only as a base for other classes.
Abstract methods 2: Abstract classes can define abstract methods, which contain no implementation, only their signature.
Derived classes are obliged to provide the implementation for all abstract methods of the base class.
3. Concrete methods: An abstract class may also contain concrete methods, that is, fully implemented methods that can be used or overridden in derived classes.
4. Constructors: An abstract class can have a constructor that can be invoked by daughter classes using parent::__construct().
Syntax of an abstract class in PHP:
abstract class Animal {
// Abstract method: derived classes must implement this method
abstract public function emitSound();
// Concrete method: derived classes can use it as is or override it
public function sleep() {
echo“Zzz;
}
}
class Dog extends Animal {
// Implementation of the abstract method
public function emitSound() {
echo“Woof!“
}
}
class Cat extends Animal {
// Implementation of the abstract method
public function emitSound() {
echo“Meow!“
}
}
// Using derived classes
$cane = new Dog();
$cane->emitSound(); // Output: Woof!
$cane->sleep(); // Output: Zzz…
$cat = new Cat();
$cat->emitSound(); // Output: Meow!
$cat->sleep(); // Output: Zzz…
?>
Explanation:
-The Animal class is abstract and cannot be instantiated directly.
-Defines an abstract method emitSound() to be implemented by the derived classes(Dog and Cat).
-It also defines a concrete method dormi(), which can be used as is by derived classes.
-The classes Dog and Cat extend Animal and provide their own implementation of the emitSound() method.
When to use an abstract class?
Abstract classes are useful when you want to define a common structure for a set of classes that share similar characteristics, but you also want to be sure that each child class implements some specific methods.
In PHP, final is a keyword that is used to define properties and methods that cannot be overridden in derived classes.
The use of final is important to maintain the integrity and consistency of the behavior of certain classes or methods in an application.
Final property
In PHP, you cannot declare a property as final directly.
The keyword final is used only for methods and classes, not for properties.
However, you can use visibility(private, protected, public) to control how properties are used or overridden in derived classes.
Final methods
A final method is a method that cannot be overridden in a derived class.
If a daughter class attempts to override a method declared as final in the parent class, PHP will generate a fatal error.
Example:
class BaseClass {
final public function sayHello() {
echo“Hello from BaseClass;
}
}
class DerivedClass extends BaseClass {
// This will cause an error because sayHello is final in the base class
public function sayHello() {
echo“Hello from DerivedClass.”
}
}
In this example, the sayHello() method is declared as final in the BaseClass class, so it cannot be overridden in the DerivedClass class.
Final classes
When a class is declared final, it means that it cannot be extended or inherited from other classes.
No derived class can be created from a final class.
Example:
final class BaseClass {
public function sayHello() {
echo“Hello from BaseClass;
}
}
// This will cause an error because BaseClass is final and cannot be inherited
class DerivedClass extends BaseClass {
}
In this case, the BaseClass class is declared as final, so it cannot be extended by any other class, and PHP will generate an error if you try to extend it.
Summary of key concepts:
-Final methods: A method defined as final cannot be overridden by a derived class.
-Final classes: A class declared final cannot be extended by other classes.
-Final Properties: There is no syntax for declaring a property as final in PHP; visibility can be used to control access to properties in child classes.
In PHP, static properties and methods are associated with a class rather than a specific instance of that class.
This means that they can be accessed directly through the class name, without having to create an object of that class.
Here is a detailed overview:
1. Static Properties
A static property is a variable associated with a class, accessible directly through the class itself and not through its instances.
It is declared using the static keyword.
Example of declaration and use of a static property:
class Example {
public static $propertyStatic=“Static value“;
public static function printValue() {
echo self::$propertyStatic;
}
}
// Access the static property via the class name
echo Example::$propertyStatic; // Output: Static value
// Modification of the static property
Example::$propertyStatic = “New value”;
Example::printValue(); // Output: New Value
Characteristics of static properties:
-Static properties cannot be accessed through an instance of the class, but only through the class itself.
-They are shared among all instances of the class.
If the static property is changed, the change is reflected in all instances of the class.
2. Static Methods
A static method is a method that belongs to the class and can be called without creating an instance of the class.
It is declared with the static keyword.
Example of declaration and use of a static method:
class Math {
public static function sum($a, $b) {
return $a + $b;
}
}
// Call to static method without creating an instance of the class
echo Math::sum(3, 4); // Output: 7
Characteristics of static methods:
-Static methods cannot access non-static class properties (i.e., instance properties) or use $this, since there is no specific object that $this can refer to .
-They can, however, access static properties and other static methods of the same class.
3. Keyword self and static
-Within a static method, the self keyword is used to refer to the class itself. self is useful for accessing properties or static methods defined in the class itself.
–self refers to the class in which the static method is declared, while static refers to the class in which the method is called.
This is especially important when working with inheritance.
Example of the use of self and static:
class Base {
public static function method() {
echo“Method in the Base class;
}
public static function callMethod() {
self::method(); // Refers to the method of the Base class
}
}
class Derivate extends Base {
public static function method() {
echo “Method in the Derived class.”
}
}
Derivate::callMethod(); // Output: Method in the Base class.
In the case above, self::method() within Base refers to Base::method(), not to Derivate::method(), even though callMethod() is called via Derivate.
Difference between self and static:
If instead you use static:: instead of self::, you will get the behavior bound to the derived class, taking advantage of Late Static Binding:
class Base {
public static function method() {
echo“Method in the Base class;
}
public static function callMethod() {
static::method(); // Uses Late Static Binding
}
}
class Derivate extends Base {
public static function method() {
echo“Method in the Derived class.”
}
}
Derivate::callMethod(); // Output: Method in the Derivate class.
4. Access Modifiers (public, protected, private)
-Static properties and methods can be declared as public, protected or private, using normal access modifiers.
-A static method or property declared as private will be accessible only within the class itself, while one declared as protected will also be accessible from derived classes.
Conclusion
Static properties and methods in PHP are powerful tools for managing data and behavior at the class level, without the need to create objects.
They are useful for implementing class constants, utility methods (such as math functions), or properties shared among all instances of the class.
Leave A Comment