Abstract
The 'abstract' keyword is used to say that a method or class cannot be created in your program as it stands. This does not stop people inheriting from that abstract class to create a new, non-abstract (concrete) class.
Consider this code:
$p = new A;
The code is perfectly legal we have a class A, and we're creating one instance of that and assigning it to $p. However, given that we have actual breeds of A to choose from, what this code actually means is "create a A with no particular breed." Even mongrels have breed classifications, which means that a 'A' without a breed is impossible and should not be allowed. We can use the abstract keyword to enforce this in code:
abstract class A {
private $Name;
// statement here
$p = new A;
The A class is now abstract, and $p is now being created as an abstract 'A' object. PHP now halts execution with a fatal error message: "Cannot instantiate abstract class 'A' ".
As mentioned already, you can also use the abstract keyword with methods, but if a class has at least one abstract method, the class itself must be declared abstract. Also, you will get errors if you try to provide any code inside an abstract method, which makes this illegal:
abstract class A{
abstract function say( ) {
print "Hello!";
}
}
It even makes this illegal:
abstract class A {
abstract function say( ) { }
}
Instead, a proper abstract method should look like this:
abstract class A {
abstract function say( );
}
0 comments:
Post a Comment