We can not create object of the abstract class using new keyword. Also we can not call the abstract methods directly as we can’t create a object of that class.
Abstract class can be used some what like an interface in PHP. So basically we can implement class using abstract. We can’t extend more than one abstract class while we can implement more than one interface.abstract class vehicle()
{
}
$new_vehicle = new vehicle();
// This will give following error:
// Fatal error: Cannot instantiate abstract class
{
}
$new_vehicle = new vehicle();
// This will give following error:
// Fatal error: Cannot instantiate abstract class
Declaring Abstract Method.
Abstract method can be declared using abstract keyword. abstract method must not contain implementation part. We can just declare it.
abstract class vehicle()
{
abstract function set_name() {}
}
// This will end up with below Error:
// Fatal error:
// Abstract function vehicle::set_name() cannot contain body
{
abstract function set_name() {}
}
// This will end up with below Error:
// Fatal error:
// Abstract function vehicle::set_name() cannot contain body
Example with abstract Class and Method.
abstract class vehicle()
{
abstract function set_name();
}
{
abstract function set_name();
}
We have to extend an abstract class to use the methods of that class. To call the abstract method you must extend the class which contain that abstract method and implementation code can be written in child class.
Child class must have to implement all abstract methods of the parent class. And the access level of the methods of the child class must be same or lower. So if abstract method is declared as public in abstract class then you can’t implement it as a protected or private in child class.
abstract class vehicle
{
abstract function set_name();
}
class bike extends vehicle
{
function set_name()
{
echo "Yamaha";
}
}
$obj_bike = new bike();
$obj_bike->set_name();
// Output : Yamaha
No comments:
Post a Comment