> php教程 > PHP开发 > 본문

PHP 객체지향 프로그래밍의 고급 기능(인터페이스, 상속, 추상 클래스, 파괴, 복제 등)에 대한 자세한 설명

高洛峰
풀어 주다: 2016-12-30 10:01:41
원래의
1663명이 탐색했습니다.

이 기사의 예에서는 PHP 객체 지향 프로그래밍의 고급 기능을 설명합니다. 다음과 같이 참조할 수 있도록 모든 사람과 공유하십시오.

정적 속성

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

출력: 0 hello

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

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)
로그인 후 복사

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

상수 속성

<?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)를 구현해야 합니다.

상속된 클래스 및 인터페이스

<?php
class TimedService{ }
interface Bookable{ }
interface Chargeable{ }
class Consultancy extends TimedService implements Bookable, Chargeable { // 继承类与接口
  // ...
}
?>
로그인 후 복사

추상 클래스

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

<?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
(
)
로그인 후 복사

Static method

<?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
)
로그인 후 복사

최종 필드

클래스를 상속할 수 없게 만들고 많이 사용되지 않음

<?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( )

소멸자

<?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; ); // 最后执行析构函数,使用完之后执行
?>
로그인 후 복사

출력:

아무 작업도 하지 않음

__clone 메서드

복제 시

<?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
?>
로그인 후 복사

댓글: 학습은 여전히 ​​두뇌를 확장할 수 있습니다. 오늘 드디어 여러 화살표 개념이 있는 이유를 이해했습니다. 계정->잔액. 여기서 계정 속성은 객체입니다.

__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은 개체를 출력합니다.

Person Object()

이 글이 PHP 프로그래밍에 종사하는 모든 분들께 도움이 되기를 바랍니다.

PHP 객체지향 프로그래밍의 고급 기능(인터페이스, 상속, 추상 클래스, 파괴, 복제 등)에 대한 자세한 설명은 PHP 중국어 웹사이트를 참고하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!