| 
	
 | 
 Posted by Oliver Grδtz on 10/24/05 16:48 
GamblerZG schrieb: 
>>But what benefit is there is having it as an explicitly "abstract" 
>>class? Why can't it just be a "normal" class definition which you 
>>inherit from? 
>  
> The idea is that a high-level language should prohobit you from doing  
> things that do not make sence. Why they implemented it in PHP? Because  
> it's there in Java, I guess. 
 
No, it's there because it makes sense. 
If you derive from an abstract class the mechanism forces you to 
implement the abstract methods. Think of this: 
 
class Super 
{ 
  public function check() {} //no code! 
  public function huba() 
  { 
    /* code */ 
    $this->check(); // use of method 
  } 
} 
class MyClass extends Super {} 
 
This is what you do without having abstract classes. You put an empty 
method into the class. You rely on remembering that test() has to be 
filled with meaning in the subclass. You are even allowed to forget 
implementing check() which might get you into trouble because the 
check() is what you meant to be called for ensuring the data integrity 
of the data you intend to use a few lines later. 
 
Or worse: You leave out the method in the superclasse and only state in 
the documentation that there has to be a check() method in subclasses. 
This is the way to forgetting to implement all kinds of stuff. 
 
So there is this mechanism called "abstract class": 
 
abstract class Super 
{ 
  abstract public function check(); 
  public function huba() 
  { 
    /* code */ 
    $this->check(); // use of method 
  } 
} 
class MyClass extends Super {} 
 
Now, you enforce several things: 
- Super cannot be instantiated. 
  It is not complete and PHP knows about this. 
- MyClass is not complete until you implement a check(). 
  This way you have to actively say "I don't need a check." 
  by putting an empty check() into MyClass. 
 
Even better: You can decide to implement just some of the abstract 
methods of Super. Then PHP forces you to declare your subclass as 
abstract, too. This allows for partially complete class trees and it is 
not up to you to remember which classes are ready to use and which are not. 
 
No, abstract classes are not just there "because Java has them", they 
exits because they help you in managing your code repository and because 
they prohibit you from doing stupid things with the code. 
 
OLLi
 
  
Navigation:
[Reply to this message] 
 |