We can declare methods and constants in interface. Make sure that declared method must have only declaration part and not the implementation part. Also all methods declared in interface must be public.
Interface can be implemented using implements operator. All methods declared in the interface must be implemented in class which implement that interface.
It will generate Fatal Error if you do not implement the method which declared in an interface. Please check below code which shows the implementation of the interface.
Create Interface
We can create an interface using the keyword interface. Check out below code that will demonstrate the code to create an basic interface..
interface first_interface
{
public function first_method($name);
public function second_method();
}
{
public function first_method($name);
public function second_method();
}
You can see that above interface have 2 methods declared. So any class which implement this interface must declare those two methods.
Implementing the Interface
Implementing the Interface
It will generate Fatal Error if you do not implement the method which declared in an interface. Please check below code which shows the implementation of the interface.
interface first_interface
{
public function first_method($name);
public function second_method();
}
class new_class implements first_interface
{
public function first_method($name)
{
// Code goes Here for method
}
public function second_method()
{
// Code goes Here for method
}
}
We can implement more than one interface to one class. In this case interface names should be separated by comma ,.
class new_class implements first_interface, second_interface
{
// Code for the class goes here.
}
{
// Code for the class goes here.
}
No comments:
Post a Comment