Search code examples
phpoopinheritancescope-resolution

how to call parent class method in php


This is the working code, but i want to know without using another object(commented $foo) how could i use printItem() method of class Foo using the $bar object. New to oop programming concept so may be a weak thing to ask but really unable to locate :(

I use scope resolution operator to use printItem() of Foo class, now my query is when we can use this functionality then what is the use of creating objects ? When to use scope resolution operators in proper coding environment.

<?php

class Foo
{
    public function printItem($string)
    {
        echo "This is in class Foo ". $string ."<br />";
    }

    public function printPHP()
    {
        echo "PHP is great "."<br />";
    }
}

class Bar extends Foo
{
    public function printItem($string)
    {
        echo "This is in class Bar ". $string ."<br />";
    }
}       

//$foo = new Foo;
$bar = new Bar;

$bar->printPHP();
$bar->printItem("Bar class object");
//Foo::printItem("Mental Case");

Solution

  • define printItem as static method and you can use Foo::printItem("Mental Case"); or call it in child method:

    public function printItem($string)
    {
        parent::printItem($string);
        echo "This is in class Bar ". $string ."<br />";
    }