在另一个文件中扩展类的正确方法是什么? [英] What is the proper way to extend a class in another file?

查看:98
本文介绍了在另一个文件中扩展类的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我在foo.php中拥有的

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

这是我在foo3.php中拥有的

This is what I have in foo3.php

class Foo3 extends Foo
{
    public $foo3 = NULL;

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

这就是我在第三个文件run.php中要求它的方式:

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");

我收到此错误:

致命错误:调用未定义的方法Foo :: setFoo3()

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

我不确定问题是否出在我对它们的需求方式上.谢谢.

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

推荐答案

在您的示例中,您将实例化Foo,它是父级,并且不知道方法setFoo3().试试这个:

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");

这篇关于在另一个文件中扩展类的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆