Q:

PHP find output programs (Class & Objects) | set 3

0

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";
?>

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer 1:

Output:

PHP Fatal error:  Uncaught Error: Call to protected method Sample::fun() 
from context '' in /home/main.php:11
Stack trace:
#0 {main}
  thrown in /home/main.php on line 11

Explanation:

The above code will generate syntax error because we cannot access protected member outside the class.

Answer 2:

Output:

Fun() called

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:

Fun() called

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:

PHP Parse error:  syntax error, unexpected '->' (T_OBJECT_OPERATOR) 
in /home/main.php on line 12

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now