Find the output of PHP programs | Class & Objects | Set 3: Enhance the knowledge of PHP Class & Objects by solving and finding the output of some PHP programs.
Question 1:
<?php
class Sample
{
protected function fun()
{
echo "Fun() called<br>";
}
}
$obj = new Sample();
$obj->fun();
?>
Question 2:
<?php
class Sample
{
public function fun()
{
echo "Fun() called<br>";
}
}
(new Sample())->fun();
?>
Question 3:
<?php
class Sample
{
static public function fun()
{
echo "Fun() called<br>";
}
}
Sample::fun();
?>
Question 4:
<?php
class Sample
{
public function fun()
{
echo "Fun() called<br>";
}
}
S;
S->fun();
?>
Question 5:
<?php
class Sample
{
public function fun()
{
echo "Fun() called<br>";
}
}
$S = new Sample();
if ($S instanceof Sample)
echo "Hello";
else
echo "Hiii";
?>
Answer 1:
Output:
Explanation:
The above code will generate syntax error because we cannot access protected member outside the class.
Answer 2:
Output:
Explanation:
In the above program, we created a class Sample that contains a public method fun().
The above program, will call method fun(), because (new Sample()) will return the object. Herem we created anonymous object to call method fun().
Answer 3:
Output:
Explanation:
In the above program, we created a class Sample that contains a static method fun(), And we called function fun() using scope resolution operator (::), that will print "Fun() called" on the webpage.
Answer 4:
Output:
Explanation:
The above program will generate syntax error, we cannot create an object like, this is the C++ style for object creation. But it is not supported in PHP.
Answer 5:
Output:
Hello
Explanation:
In the above program, we created a class Sample that contains method fun(), then we created the object of class Sample. Here, we used the instanceof keyword, which is used to check an object belongs to class or not. Here, object $S belongs to the class Sample, then "Hello" will be printed on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer