PHP:将一个类函数包含在另一个类函数中

时间:2018-01-08 01:25:44

标签: php

我有大班foo,我想分成两个单独的类(和文件);

我的班级foo使用contruct函数和noumerous $this引用。

我需要第二个班级bar作为原始foo班级的扩展,因此如果要包含bar类,我仍然可以使用带有附加参数的构造;

$includeBar = true;
$foo = new foo($config, $includeBar);

我试过这样说:

Class bar extends foo {

   public function barFunction(){
      //some function of bar
   }
}


Class foo {

   public function __construct($config, $includeBar = true) {
      if ($includeBar) {
         include_once 'bar.php';
      }
   }

}

但是当我打电话时:

$foo = new foo($config, true);
$foo->barFunction();

它失败了,说

PHP Fatal error: Uncaught Error: Call to undefined method foo::barFunction()

我做错了什么?请帮忙,卡住了

2 个答案:

答案 0 :(得分:2)

反过来应该是相反的 Bar是您的基类,它包含每个子类也需要的所有方法。 Foo是扩展,额外的,所以Foo扩展了Bar。

<?php 

// file bar.php
Class Bar {
    public function __construct($config) {
         $this->config = $config;
    }

    public function barFunction() {
        echo "I'm everybody ".$this->config['msg'];
    }
}

// file foo.php
require_once('bar.php');

Class Foo extends Bar {
    public function fooOnly() {
        echo "I'm foo ".$this->config['msg'];
    }   
}


// consuming file index.php
include('foo.php');
$config = array('msg'=>'and I need coffee');
$foo = new foo($config);
$foo->barFunction();  // we can call this, because foo extends bar

// this won't work:
$bar = new Bar($config);
$bar->fooOnly();

// but this:
$bar->barFunction();
$foo->fooOnly();

(使用合适的自动加载器时,可以省略所有包含/要求!)

答案 1 :(得分:0)

如果您想要重用类方法或单独的类方法实现,我认为您可以使用trait,然后您可以使用关键字use来为您的类提供函数。

例如:

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

以上示例将输出:

Hello World!
相关问题