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

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;
    }
}  

Here is how I need it in my third run.php file:

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

I get this error:

Fatal error: method call undefined Foo :: setFoo3 ()

I'm not sure the problem is how I require them. Thank.

+5
source share
3 answers

In your example, you create an instance Foothat is parent and does not know the method setFoo3(). Try the following:

class Foo3 extends Foo
{
    ...
}

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

-, foo.php public, setFoo($foo1, $foo2). - :

<?php

class Foo
{
    private $foo1;
    private $foo2;

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

extends Foo3, . - foo3.php:

<?php

require_once "foo.php";

class Foo3 extends Foo
{
    public function setFoo3($foo3) {
        $this->setFoo($foo3, "some foo3 specific value"); // calling superclass method
    }
}

Foo3 run.php :

<?php

require_once "foo3.php";

$foo3 = new Foo3();
$foo3->setFoo3("bar");

, ;)

+8

, . Foo, foo3 . Foo foo3.

+1

All Articles