0

How can I access function of class B, when I have instantiated class A, Instead of making abstract class? what is the simplest solution to this problem?

    class A
    {
        public $a = 3;
        public function addup($var)
        {
            return ($var + $var);
        }
    }

    class B extends A
    {
        public function addup1($var)
        {
            return ($var * $var);
        }
    }


    $obj = new A();
    echo "Func from Class A: " . $obj->addup(3);
    echo "<br>";
    echo $obj->addup1(3);
    echo "<br><br><br><br>";



    $obj = new B();
    echo "Func from Class A: " . $obj->addup(3);
    echo "<br>";
    echo "Func from Class B: " . $obj->addup1(3);

    ?>
Ebad Masood
  • 2,389
  • 28
  • 46
Sam
  • 376
  • 3
  • 10

1 Answers1

2

Normally you can/should not. If you have a class car for example:

class Car {
    public function drive() {
        ...
    }
}

The car can basically only drive. He doesn't know any other actions. Car doesn't know anything about other classes extending it. Let's now extend the Car by creating a Batmobile.

class Batmobile extends Car {
    public function shoot() {
        ...
    }
}

The Batmobile has the ability to shoot with a machine gun. This is in addition to all the Car can do (drive in this case). A normal car on the other hand $fiat = new Car(); is not a batmobile, and therefore cannot shoot.

Back to your case. If you have an instance of A, all its functions are defined within this class. It does not have the method addup1(). You have multiple options right now:

  1. Redesign your class, maybe the inheritance is not properly done. Or maybe the method addup1() can be moved to class A.
  2. On php.net someone posted a comment (which I don't find very accurate). Nonetheless you could, as long as addup1() does NOT access any attributes of B, create the method in A and just call the one in B... See this comment.

Even though you could do the second solution, I would not recommend it. It is against the idea of inheritance. It's better to rethink about the classes and maybe change them somewhat.

Slomo
  • 1,224
  • 8
  • 11