如何使用PHP抽象? [英] How to work with PHP abstract?

查看:63
本文介绍了如何使用PHP抽象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您为什么要使用这样的摘要?它会加快工作速度还是它的作用到底是什么?

Why would you use such abstract? Does it speed up work or what exactly its for?

// file1.php
abstract class Search_Adapter_Abstract {
    private $ch = null;
    abstract private function __construct()
    {
    }       
    abstract public funciton __destruct() { 
      curl_close($this->ch);
    }
    abstract public function search($searchString,$offset,$count);
}

// file2.php
include("file1.php");
class abc extends Search_Adapter_Abstract
{
    // Will the curl_close now automatically be closed?

}

在这里扩展摘要的原因是什么?让我感到困惑.我现在可以从中得到什么?

What is the reason of extending abstract here? Makes me confused. What can i get from it now?

推荐答案

您可以使用抽象类来定义并部分实现扩展类应执行的常见任务.由于没有示例很难解释,因此请考虑以下问题:

You can use abstract classes to define and partially implement common tasks that an extended class should do. Since explaining it is difficult without an example, consider this:

没有抽象类,您将必须定义两个具有相同方法和实现的基本类.由于OOP都是关于防止代码重复的,所以这是完全错误的:

Without abstract classes, you would have to define two basic classes with the same methods and implementation. Since OOP is all about preventing code duplication, this is quite wrong:

class Car {
  public $brand = 'mercedes';

  public function gasPerMile($weight) 
  {
    // Useless calculation, purely for illustrating
    $foo = $weight * 89 / 100;
    return $foo;
  }

  public function carSpecificFunction() 
  {
    // Only present in class Car
  }
}

class Truck {
  public $brand = 'MAN';

  public function gasPerMile($weight) 
  {
    // Useless calculation, purely for illustrating
    $foo = $weight * 89 / 100;
    return $foo;
  }

  public function truckSpecificFunction() 
  {
    // Only present in class Truck
  }
}

现在,您具有一些通用的属性和方法,它们在两个类中重复.为了防止这种情况,我们可以定义一个抽象类,从中扩展CarTruck.这样,通用功能就被保留在一个地方,扩展类将为卡车或轿车实现特定的属性和方法.

Now you have some common properties and methods, which are duplicated in two classes. To prevent that, we could define an abstract class from which Car and Truck are extended. This way, common functionalities are kept in one place and the extended classes will implement specific properties and methods for either the Truck or the Car.

abstract class Vehicle {
  abstract public $brand;

  public function gasPerMile($weight) 
  {
    // Useless calculation, purely for illustrating
    $foo = $weight * 89 / 100;
    return $foo;
  }
}

这样,您可以确保至少每个扩展Vehicle的类都必须指定一个品牌,并且所有扩展类都可以使用通用的gasPerMile()方法.

This way, you ensure that atleast every class that extends Vehicle has to have a brand specified and the common gasPerMile() method can be used by all extended classes.

当然,这是一个简单的示例,但希望它能说明为什么抽象类有用的原因.

Of course, this is a simple example, but hopefully it illustrates why abstract classes can be useful.

这篇关于如何使用PHP抽象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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