| Start |
|---|
| Class Constants Class constants provide a mechanism for holding fixed values in a program. That is, they provide a way of giving a name (and associated compile-time checking) to a value like As an example, it may be convenient to have a shorthand representation for the value of π throughout a program. A class with Class constants may be accessed by using the double colon operator (so-called the scope resolution operator) on a class, much like static variables. Unlike static variables, however, class constants have their values fixed at compile time and cannot be reassigned to (e.g. Class constants are also useful for defining things internal to a class that might need changing later (but do not change frequently enough to warrant storing in, say, a database). We can reference this internally using the Class constants can only contain scalar values in versions < 5.6 As of PHP 5.6 we can use expressions with constants, meaning math statements and strings with concatenation are acceptable constants As of PHP 7.0, constants declared with Class constants are useful for more than just storing mathematical concepts. For example, if preparing a pie, it might be convenient to have a single We can then use the The problem that arises here is, when instantiating the Listing the acceptable values as class constants provides a valuable hint as to the acceptable values which a method accepts. It also ensures that misspellings cannot make it past the compiler. While Finally, using class constants means that the actual value of the constant may be modified in a single place, and any code using the constant automatically has the effects of the modification. Whilst the most common method to access a class constant is Class constants in PHP are conventionally named all in uppercase with underscores as word separators, although any valid label name may be used as a class constant name. As of PHP 7.1, class constants may now be defined with different visibilities from the default public scope. This means that both protected and private constants can now be defined to prevent class constants from unnecessarily leaking into the public scope (see Method and Property Visibility (opens new window) ). For example: define vs class constantsAlthough this is a valid construction: If you try to do the same with class constants, you'll get an error: But you can do: For more information, see constants in the manual (opens new window). Using ::class to retrieve class's namePHP 5.5 introduced the The above works even if the classes are not even defined (i.e. this code snippet works alone). This syntax is useful for functions that require a class name. For example, it can be used with |
| Abstract Classes An abstract class is a class that cannot be instantiated. Abstract classes can define abstract methods, which are methods without any body, only a definition: Abstract classes should be extended by a child class which can then provide the implementation of these abstract methods. The main purpose of a class like this is to provide a kind of template that allows children classes to inherit from, "forcing" a structure to adhere to. Lets elaborate on this with an example: In this example we will be implementing a To ease the development of further Worker implementations, we will create an abstract worker class
that already provides the First of all, we have provided an abstract method Secondly the Finally, all of these method calls have been grouped in a Now lets define a child class that extends from the As you can see, the Important NoteWhen inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child (or the child itself must also be marked abstract); additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Taken from the PHP Documentation for Class Abstraction (opens new window). If you do not define the parent abstract classes methods within the child class, you will be thrown a Fatal PHP Error like the following. **Fatal error:** Class X contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (X::x) in |
| Late static binding In PHP 5.3+ and above you can utilize late static binding (opens new window) to control which class a static property or method is called from. It was added to overcome the problem inherent with the You would expect that the The problem is that |
| Namespacing and Autoloading Technically, autoloading works by executing a callback when a PHP class is required but not found. Such callbacks usually attempt to load these classes. Generally, autoloading can be understood as the attempt to load PHP files (especially PHP class files, where a PHP source file is dedicated for a specific class) from appropriate paths according to the class's fully-qualified name (FQN) when a class is needed. Suppose we have these classes: Class file for Class file for Class file for Under the source folder, these classes should be placed at the paths as their FQNs respectively:
|
Interfaces IntroductionInterfaces are definitions of the public APIs classes must implement to satisfy the interface. They work as "contracts", specifying what a set of subclasses does, but not how they do it. Interface definition is much alike class definition, changing the keyword Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract: Note: interfaces must not declare constructors or destructors, since these are implementation details on the class level. RealizationAny class that needs to implement an interface must do so using the A single class can implement more than one interface at a time. When abstract classes implement interfaces, they do not need to implement all methods. Any method not implemented in the base class must then be implemented by the concrete class that extends it: Notice that interface realization is an inherited characteristic. When extending a class that implements an interface, you do not need to redeclare it in the concrete class, because it is implicit. **Note:** Prior to PHP 5.3.9, a class could not implement two interfaces that specified a method with the same name, since it would cause ambiguity. More recent versions of PHP allow this as long as the duplicate methods have the same signature[[1]](http://php.net/manual/en/language.oop5.interfaces.php). InheritanceLike classes, it is possible to establish an inheritance relationship between interfaces, using the same keyword ExamplesIn the example bellow we have a simple example interface for a vehicle. Vehicles can go forwards and backwards. Then we create two classes that implement the interface: Bike and Car. Bike and Car internally are very different, but both are vehicles, and must implement the same public methods that VehicleInterface provides. Typehinting allows methods and functions to request Interfaces. Let's assume that we have a parking garage class, which contains vehicles of all kinds. Because |
| Method and Property Visibility There are three visibility types that you can apply to methods (class/object functions) and properties (class/object variables) within a class, which provide access control for the method or property to which they are applied. You can read extensively about these in the PHP Documentation for OOP Visibility (opens new window). PublicDeclaring a method or a property as
An example of this ProtectedDeclaring a method or a property as
This does not allow external objects, classes, or code outside the class hierarchy to access these methods or properties. If something using this method/property does not have access to it, it will not be available, and an error will be thrown. Only instances of the declared self (or subclasses thereof) have access to it. An example of this The example above notes that you can only access the PrivateDeclaring a method or a property as
A Note that objects of the same type will have access to each others private and protected members even though they are not the same instances. As noted, you can only access the |
| Final Keyword Def: Final Keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended Final Method Final Class: Final constants: Unlike Java, the Why do I have to use
When to avoid
|
| Namespacing and Autoloading Technically, autoloading works by executing a callback when a PHP class is required but not found. Such callbacks usually attempt to load these classes. Generally, autoloading can be understood as the attempt to load PHP files (especially PHP class files, where a PHP source file is dedicated for a specific class) from appropriate paths according to the class's fully-qualified name (FQN) when a class is needed. Suppose we have these classes: Class file for Class file for Class file for Under the source folder, these classes should be placed at the paths as their FQNs respectively:
|
| Dynamic Binding Dynamic binding, also referred as method overriding is an example of run time polymorphism that occurs when multiple classes contain different implementations of the same method, but the object that the method will be called on is unknown until run time. This is useful if a certain condition dictates which class will be used to perform an action, where the action is named the same in both classes. In the above example, the |
| Calling a parent constructor when instantiating a child A common pitfall of child classes is that, if your parent and child both contain a constructor( Now harnessing that within a real-world situation would look something like: The above will run the parent |
| $this, self and static plus the singleton Use `$this` to refer to the current object. Use `self` to refer to the current class. In other words, use `$this->member` for non-static members, use `self::$member` for static members. In the example below,
Consider the following code: This doesn't produce the result you want: unknown That's because To refer to the correct class, you need to use This does produce the desired output: unknown See also Late static binding (opens new window) The singletonIf you have an object that's expensive to create or represents a connection to some external resource you want to reuse, i.e. a database connection where there is no connection pooling or a socket to some other system, you can use the As you can see in the example code we are defining a private static property The We are also setting the constructor to be private to ensure that no one creates it with the To use this object you just write the following: Now I DO implore you to use dependency injection where you can and aim for loosely coupled objects, but sometimes that is just not reasonable and the singleton pattern can be of use. |
| Defining a Basic Class An object in PHP contains variables and functions. Objects typically belong to a class, which defines the variables and functions that all objects of this class will contain. The syntax to define a class is: Once a class is defined, you can create an instance using: Variables and functions on the object are accessed like this: ConstructorClasses can define a special Extending Another ClassClass definitions can extend existing class definitions, adding new variables and functions as well as modifying those defined in the parent class. Here is a class that extends the previous example: The |
| Anonymous Classes Anonymous classes were introduced into PHP 7 to enable for quick one-off objects to be easily created. They can take constructor arguments, extend other classes, implement interfaces, and use traits just like normal classes can. In its most basic form, an anonymous class looks like the following: Nesting an anonymous class inside of another class does not give it access to private or protected methods or properties of that outer class. Access to protected methods and properties of the outer class can be gained by extending the outer class from the anonymous class. Access to private properties of the outer class can be gained by passing them through to the anonymous class's constructor. For example: Syntax
RemarksClasses and Interface componentsClasses may have properties, constants and methods.
Interfaces cannot have properties, but may have constants and methods.
|
Read Article
https://develop.horje.com/learn/1434/reference