PHP Interview questions


Total available count: 33
Subject - PHP Frameworks
Subsubject - PHP

What is overloading in PHP?

Overloading in PHP

As we know that we can not implement overloading by create 2 functions in with same name in class. To implement overloading in PHP we will take help of magic method ‘call’. Magic method ’call’ invoked when method called by class object is not available in class. Here we will not create method exactly and will take help of ‘call’ method. Now call method will provide us 2 arguments, 1st name of the method called and parameter of the function. Now with the help of either switch , case or if else we will implement overloading in PHP. Below is simple example of overloading in PHP.

class Slightbook
{
	public function __construct()
	{
		//Ur logic for constructor
	}
	public function __call($method_name , $parameter)
	{
		if($method_name == "overlodedFunction") //Function overloading
		function name overlodedFunction
		{
		$count = count($parameter);
		switch($count)
		{
		case "1":
		//Business log in case of overlodedFunction function has 1 argument
		echo "You are passing 1 argument.";
		break;
		case "2": //Incase of 2 parameters
		echo "You are passing 2 parameters";
		break;
		default:
		throw new exception("Bad argument.");
		}
		}
		else
		{
		throw new exception("Function $method_name does not exists. ");
		}
    }
}

$a = new Slightbook();
$a->overlodedFunction("Interview questions");
$a->overlodedFunction("Multiple choices" , "Interview questions");
As in above class test magic method ?cal?l is implemented which is managing overloading
public function __call($method_name , $parameter)
{
	if($method_name == "overlodedFunction") //Function overloading
	function name overlodedFunction
	{
	$count = count($parameter);
		switch($count)
		{
		case "1":
			//Business log in case of overlodedFunction function has 1 argument
			echo "You are passing 1 argument.";
			break;
		case "2": //Incase of 2 parameters
			echo "You are passing 2 parameters";
			break;
		default:
			throw new exception("Bad argument.");
		}
	}
	else
	{
	throw new exception("Function $method_name does not exists. ");
	}
}

As we know that ‘call’ magic method invoked when method is not available in the class. In case of above test class example we have not created function overlodedFunction. Whenever method overlodedFunction is called ‘call’ invoked. ‘call’ pass 2 variable, first name of called method and another is parameter passed in the called function.

Now in the ‘call’ function, I have applied if condition to ensure that our business logic of overloading works only for overlodedFunction function. If block we have counted number of argument in parameter and applied business logic.




Next 5 interview question(s)

1
Does PHP support multiple inheritance?
2
Explain about various visibility in PHP?
3
What are Autoloading classes?
4
What is the difference between == and === in PHP?
5
What is the difference between self and $this?