问题
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.
回答1:
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");
回答2:
At the first, in your foo.php shouldn't mark your fields public, because you set those values inside setFoo($foo1, $foo2) method. Instead, you may have something like:
<?php
class Foo
{
private $foo1;
private $foo2;
public function setFoo($foo1, $foo2) {
$this->foo1 = $foo1;
$this->foo2 = $foo2;
}
}
Then you should add extends keyword when declaring class Foo3, and another thing you need to include extending class file in the beginning of the file. In your case you may have something like the following in your foo3.php file:
<?php
require_once "foo.php";
class Foo3 extends Foo
{
public function setFoo3($foo3) {
$this->setFoo($foo3, "some foo3 specific value"); // calling superclass method
}
}
then you can create an instantiate of a Foo3 class in your run.php like so:
<?php
require_once "foo3.php";
$foo3 = new Foo3();
$foo3->setFoo3("bar");
and my advice, you should read a little about OOP techniques ;)
回答3:
Of course that doesn't work. You've created a Foo object, and then tried to call foo3 on it. But Foo doesn't have a foo3 method.
来源:https://stackoverflow.com/questions/8088832/what-is-the-proper-way-to-extend-a-class-in-another-file