Bir soyut sınıf doğrudan örneği olamaz, ama o soyut ve non-soyut yöntemler içerebilir.
Bir soyut sınıf genişletmek ise, tüm soyut işlevleri uygulamak, ya da alt sınıf soyut yapmak için ya var.
Siz düzenli bir yöntemi geçersiz kılmak ve soyut, ama (sonunda) her soyut yöntemleri geçersiz kılmak ve onları soyut olmayan yapmalısınız olamaz.
<?php
abstract class Dog {
private $name = null;
private $gender = null;
public function __construct($name, $gender) {
$this->name = $name;
$this->gender = $gender;
}
public function getName() {return $this->name;}
public function setName($name) {$this->name = $name;}
public function getGender() {return $this->gender;}
public function setGender($gender) {$this->gender = $gender;}
abstract public function bark();
}
// non-abstract class inheritting from an abstract class - this one has to implement all inherited abstract methods.
class Daschund extends Dog {
public function bark() {
print "bowowwaoar" . PHP_EOL;
}
}
// this class causes a compilation error, because it fails to implement bark().
class BadDog extends Dog {
// boom! where's bark() ?
}
// this one succeeds in compiling,
// it's passing the buck of implementing it's inheritted abstract methods on to sub classes.
abstract class PassTheBuckDog extends Dog {
// no boom. only non-abstract subclasses have to bark().
}
$dog = new Daschund('Fred', 'male');
$dog->setGender('female');
print "name: " . $dog->getName() . PHP_EOL;
print "gender: ". $dog->getGender() . PHP_EOL;
$dog->bark();
?>
O program bombalar ile:
PHP Fatal error: Class BadDog
contains 1 abstract method and must
therefore be declared abstract or
implement the remaining methods
(Dog::bark)
Eğer baddog sınıf açıklama ise, o çıktı:
name: Fred
gender: female
bowowwaoar
Bu gibi doğrudan bir köpek veya bir PassTheBuckDog örneğini çalışırsanız:
$wrong = new Dog('somma','it');
$bad = new PassTheBuckDog('phamous','monster');
.. Bu bombalar ile:
PHP Fatal error: Cannot instantiate
abstract class Dog
ya da (eğer $ yanlış satırı yorum ise)
PHP Fatal error: Cannot instantiate
abstract class PassTheBuckDog
Ancak, soyut bir sınıf statik bir işlevini çağırabilirsiniz:
abstract class Dog {
..
public static function getBarker($classname, $name, $gender) {
return new $classname($name, $gender);
}
..
}
..
$other_dog = Dog::getBarker('Daschund', 'Wilma', 'female');
$other_dog->bark();
Bu gayet güzel çalışıyor.