What is the proper way to extend a class in another file?

diesel picture diesel · Nov 11, 2011 · Viewed 28.5k times · Source

This is what I have in foo.php

class Foo
{
    public $foo = NULL;
    public $foo2 = NULL;

    public function setFoo ($foo, $foo2)
    {
       $this->foo = $foo;
       $this->foo2 = $foo2'
    }
}

This is what I have in foo3.php

class Foo3 extends Foo
{
    public $foo3 = NULL;

    public function setFoo3 ($foo3)
    {
       $this->foo = $foo3;
    }
}  

This is how I require it in my third file run.php:

require_once "foo.php";
require_once "foo3.php";
$foo = new Foo();
$foo->setFoo3("hello");

I get this error:

Fatal error: Call to undefined method Foo::setFoo3()

I'm not sure if the problem is how I'm requiring them. Thanks.

Answer

Mike Purcell picture Mike Purcell · Nov 11, 2011

In your example, you are instantiating Foo, which is the parent and has no knowledge of the method setFoo3(). Try this:

class Foo3 extends Foo
{
    ...
}

require_once "foo.php";
require_once "foo3.php";
$foo = new Foo3();
$foo->setFoo3("hello");