>  기사  >  백엔드 개발  >  PHP 객체 지향 인터페이스, 상속, 추상 클래스, 파괴, 복제 및 기타 고급 기능의 예에 대한 자세한 설명

PHP 객체 지향 인터페이스, 상속, 추상 클래스, 파괴, 복제 및 기타 고급 기능의 예에 대한 자세한 설명

伊谢尔伦
伊谢尔伦원래의
2017-06-29 09:36:101287검색

이 글에서는 주로 PHP 객체지향프로그래밍고급 기능을 소개하고, PHP 객체지향 프로그래밍에 관련된 정적 속성, 상수 속성, 인터페이스, 상속, 추상 클래스, 소멸자를 예제와 함께 분석합니다. 다른 개념이나 활용 능력이 필요한 친구는

1. 정적 속성

<?php
class StaticExample {
  static public $aNum = 0; // 静态共有属性
  static public function sayHello() { // 静态共有方法
    print "hello";
  }
}
print StaticExample::$aNum;
StaticExample::sayHello();
?>

출력: 0 Hello

댓글: 정적 속성 및 메서드를 클래스를 통해 직접 호출할 수 있습니다.

2. SELF

<?php
class StaticExample {
  static public $aNum = 0;
  static public function sayHello() { // 这里的static 和 public的顺序可以颠倒
    self::$aNum++;
    print "hello (".self::$aNum.")\n"; // self 指向当前类, $this指向当前对象。
  }
}
StaticExample::sayHello();
StaticExample::sayHello();
StaticExample::sayHello();
?>

출력:

hello (1)
hello (2)
hello (3)

Comments: self는 현재 클래스를 가리키고, 이것은 현재 개체를 가리킵니다. self는 현재 클래스의 정적 속성과 메서드를 호출할 수 있습니다. 이는 현재 개체를 가리킵니다. self는 현재 클래스의 정적 속성과 메서드를 호출할 수 있습니다. 이는 현재 클래스의 일반 속성과 메서드를 호출할 수 있습니다.

3. 상수 속성

<?php
class ShopProduct {
  const AVAILABLE   = 0; // 只能用大写字母命名常量
  const OUT_OF_STOCK  = 1;
  public $status;
}
print ShopProduct::AVAILABLE;
?>

출력: 0

Comments: 상수는 대문자만 사용할 수 있으며 클래스를 통해 직접 호출할 수 있습니다.

4. 인터페이스

<?php
interface Chargeable { // 接口,抽象类是介于基类与接口之间的东西
  public function getPrice();
}
class ShopProduct implements Chargeable {
  // ...
  protected $price;
  // ...
  public function getPrice() {
    return $this->price;
  }
  // ...
}
$product = new ShopProduct();
?>

getPrice 메소드가 구현되지 않으면 오류가 보고됩니다.

치명적인 오류: ShopProduct 클래스에는 추상 메소드가 1개 포함되어 있으므로 추상으로 선언하거나 나머지 메소드(Chargeable::getPrice)

5를 구현해야 합니다. 상속된 클래스 및 인터페이스

<?php
class TimedService{ }
interface Bookable{ }
interface Chargeable{ }
class Consultancy extends TimedService implements Bookable, Chargeable { // 继承类与接口
  // ...
}
?>

6. 먼저 코드를 살펴보겠습니다

<?php
abstract class DomainObject {
}
class User extends DomainObject {
  public static function create() {
    return new User();
  }
}
class Document extends DomainObject {
  public static function create() {
    return new Document();
  }
}
$document = Document::create();
print_r( $document );
?>

출력:

Document Object
(
)

7. 정적 메서드

<?php
abstract class DomainObject {
  private $group; // 私有属性group
  public function construct() {
    $this->group = static::getGroup();//static 静态类
  }
  public static function create() {
    return new static();
  }
  static function getGroup() { // 静态方法
    return "default";
  }
}
class User extends DomainObject {
}
class Document extends DomainObject {
  static function getGroup() { // 改变了内容
    return "document";
  }
}
class SpreadSheet extends Document { // 继承之后,group也就与document相同了
}
print_r(User::create());
print_r(SpreadSheet::create());
?>
출력:

User Object
(
  [group:DomainObject:private] => default
)
SpreadSheet Object
(
  [group:DomainObject:private] => document
)

7은 클래스를 상속할 수 없게 만듭니다. 많이 사용됨

<?php
final class Checkout { // 终止类的继承
  // ...
}
class IllegalCheckout extends Checkout {
  // ...
}
$checkout = new Checkout();
?>
출력:

치명적인 오류: 클래스 IllegalCheckout이 최종 클래스(Checkout)에서 상속되지 않을 수 있습니다.

최종 메서드를 재정의할 수 없습니다.

<?php
class Checkout {
  final function totalize() {
    // calculate bill
  }
}
class IllegalCheckout extends Checkout {
  function totalize() { // 不能重写final方法
    // change bill calculation
  }
}
$checkout = new Checkout();
?>

출력:

치명적인 오류: 최종 메서드 Checkout을 재정의할 수 없습니다. ::totalize( )

8. Destructor

<?php
class Person {
  protected $name;
  private $age;
  private $id;
  function construct( $name, $age ) {
    $this->name = $name;
    $this->age = $age;
  }
  function setId( $id ) {
    $this->id = $id;
  }
  function destruct() { // 析构函数
    if ( ! empty( $this->id ) ) {
      // save Person data
      print "saving person\n";
    }
    if ( empty( $this->id ) ) {
      // save Person data
      print "do nothing\n";
    }
  }
}
$person = new Person( "bob", 44 );
$person->setId( 343 );
$person->setId( &#39;&#39; ); // 最后执行析构函数,使用完之后执行
?>
output:do Nothing

9.method

<?php
class Person {
  private $name;
  private $age;
  private $id;
  function construct( $name, $age ) {
    $this->name = $name;
    $this->age = $age;
  }
  function setId( $id ) {
    $this->id = $id;
  }
  function clone() { // 克隆时候执行
    $this->id = 0;
  }
}
$person = new Person( "bob", 44 );
$person->setId( 343 );
$person2 = clone $person;
print_r( $person );
print_r( $person2 );
?>
출력:

Person Object
(
  [name:Person:private] => bob
  [age:Person:private] => 44
  [id:Person:private] => 343
)
Person Object
(
  [name:Person:private] => bob
  [age:Person:private] => 44
  [id:Person:private] => 0
)

참조 또 예를 들어

<?php
class Account { // 账户类
  public $balance; // 余额
  function construct( $balance ) {
    $this->balance = $balance;
  }
}
class Person {
  private $name;
  private $age;
  private $id;
  public $account;
  function construct( $name, $age, Account $account ) {
    $this->name = $name;
    $this->age = $age;
    $this->account = $account;
  }
  function setId( $id ) {
    $this->id = $id;
  }
  function clone() {
    $this->id  = 0;
  }
}
$person = new Person( "bob", 44, new Account( 200 ) ); // 以类对象作为参数
$person->setId( 343 );
$person2 = clone $person;
// give $person some money
$person->account->balance += 10;
// $person2 sees the credit too
print $person2->account->balance; // person的属性account也是一个类,他的属性balance的值是210
// output:
// 210
?>
댓글: 학습은 여전히 ​​두뇌를 확장할 수 있습니다. 오늘은 $사람->계정->균형이라는 여러 화살표 개념이 있는 이유를 마침내 이해했습니다. 여기서 계정 속성은 객체입니다.

10.toString

<?php
class Person {
  function getName() { return "Bob"; }
  function getAge() { return 44; }
  function toString() {
    $desc = $this->getName()." (age ";
    $desc .= $this->getAge().")";
    return $desc;
  }
}
$person = new Person();
print $person; // 打印时候集中处理
// Bob (age 44)
?>

댓글: print 또는 echo일 때 유효해야 하며 print_r이 개체를 출력합니다.

위 내용은 PHP 객체 지향 인터페이스, 상속, 추상 클래스, 파괴, 복제 및 기타 고급 기능의 예에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.