【问题标题】:What are 'abstract' functions in PHP and when are they used?什么是 PHP 中的“抽象”函数以及它们何时使用?
【发布时间】:2016-03-15 03:03:13
【问题描述】:

我知道抽象类只能用作父类,不能有自己的实例,但什么是抽象函数/方法?它们的用途是什么?什么时候使用它们(一个例子)?它们的作用域(公共、私有、受保护)是如何工作的?

以下面的代码为例。

abstract class parentTest{

    //abstract protected function f1();
    //abstract public function f2();
    //abstract private function f3();

}

class childTest extends parentTest{
    public function f1(){
        echo "This is the 'f1' function.<br />";
    }

    public function f2(){
        echo "This is the 'f2' function.<br />";
    }
    protected function f3(){
        echo "This is the 'f3' function.<br />";
    }
}

$foo = new childTest();
$foo->f1();

【问题讨论】:

  • 抽象类就像接口类,你也定义了一些方法。 php.net/abstract
  • 我建议你阅读一些关于 php 或一般的 oop 编程的入门教程。可以肯定的是,这个问题在那里得到了回答。包括示例。

标签: php class oop extend


【解决方案1】:

抽象函数是在超(抽象)类中定义契约的方法签名。该契约必须由任何子类实现。方法实现在子类中的可见性必须与超类的可见性相同或限制较少。请看Class Abstraction - PHP Manual

注意:可见性与范围不同。可见性是关于隐藏在 OOP 上下文中的数据。范围更笼统。它是关于(在代码中)定义变量的位置。

【讨论】:

    【解决方案2】:

    理论上,当您想在继承实例之间共享方法时,会使用抽象方法。例如,假设您有一个代表视图的抽象类,并且每个继承类都必须渲染一些东西,您可以在父抽象类中定义方法,并且所有子类都可以访问它:

    abstract class Template {
        public function render($template) {
            include($template);
        }
    }
    class SiteView extends Template {
        protected $title = "default title";
    }
    $siteView = new SiteView();
    $siteView->render('path/to/site/template.html');
    

    为了改善这一点,您还可以使用接口并开始对您的类进行类型提示:

    interface Renderer {
        public function render($template);
    }
    abstract class Template implements Renderer {
        public function render($template) {
            include($template);
        }
    }
    class SiteView extends Template {
        protected $title = "default title";
        protected $body= "default body";
    }
    class Controller {
        private $view;
        public function __construct(Renderer $view) {
            $this->view = $view;
        }
        public function show() {
            $this->view->render('path/to/site/template.html');
        }
    }
    $siteView = new SiteView();
    $controller = new Controller($siteView);
    $controller->show();
    

    请注意控制器是如何从抽象类和具体类中分离出来的,而抽象类允许您与继承的视图共享渲染功能。如果您决定创建其他抽象类来表示其他渲染方式,控制器将继续工作。

    对于记录,模板如下所示:

    <!DOCTYPE html>
    <html>
    <head>
        <title><?= $this->title ?></title>
    </head>
    <body><?= $this->body ?></body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 2011-07-04
      • 2011-10-02
      • 2021-05-26
      • 2016-12-18
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多