이 글은 주로 PHP 객체지향 상속의 사용법을 소개하고, 코드 최적화와 코드 중복 감소를 위한 예제와 관련 운영 기법을 통해 PHP 객체지향 프로그래밍에서의 상속 사용을 분석합니다. 도움이 필요한 친구들은 이 글을 참고하세요
예제에서는 PHP의 객체 지향 상속 사용을 설명합니다. 참조를 위해 모든 사람과 공유하세요. 세부 사항은 다음과 같습니다.
Inheritance
두 클래스를 먼저 살펴보겠습니다
<?php class CdProduct { public $playLength; // 播放时间 public $title; public $producerMainName; public $producerFirstName; public $price; function __construct( $title, $firstName, $mainName, $price, $playLength ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; $this->playLength = $playLength; } function getPlayLength() { return $this->playLength; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; $base .= ": playing time - {$this->playLength}"; return $base; } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } } class BookProduct { public $numPages; // 看的页数 public $title; public $producerMainName; public $producerFirstName; public $price; function __construct( $title, $firstName, $mainName, $price, $numPages ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; $this->numPages = $numPages; } function getNumberOfPages() { return $this->numPages; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; $base .= ": page count - {$this->numPages}"; return $base; } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 ); print $product1->getSummaryLine(); print "\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); print $product2->getSummaryLine(); print "\n"; ?>
출력:
cd1 (bobbleson, bo 비) : 재생 시간 - 50
book1(harrelson, harry): 페이지 수 - 30
댓글: 이 두 카테고리의 코드 중복이 너무 높아 유사점과 차이점이 있습니다. 프로세스를 단순화하려면 상속을 사용하는 것이 좋습니다.
상속을 사용하여 처리
<?php class ShopProduct { public $numPages; public $playLength; public $title; public $producerMainName; public $producerFirstName; public $price; function __construct( $title, $firstName, $mainName, $price, $numPages=0, $playLength=0 ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; $this->numPages = $numPages; $this->playLength = $playLength; } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } function getSummaryLine() { $base = "$this->title ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { function getPlayLength() { // 增加属于自己的方法 return $this->playLength; } function getSummaryLine() { // 改造了父类的方法 $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; $base .= ": playing time - {$this->playLength}"; return $base; } } class BookProduct extends ShopProduct { function getNumberOfPages() { return $this->numPages; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; $base .= ": page count - {$this->numPages}"; return $base; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, null, 50 ); print $product1->getSummaryLine(); print "\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); print $product2->getSummaryLine(); print "\n"; ?>
출력:
cd1(bobbleson, bob): 재생 시간 - 50
book1(harrelson, harry): 페이지 수 - 30
포인트 댓글 : 상속 처리는 차이점과 호환성 문제를 매우 잘 해결합니다.
추가 최적화
<?php class ShopProduct { // 抽离出共有属性 public $title; public $producerMainName; public $producerFirstName; public $price; function __construct( $title, $firstName, $mainName, $price ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { // 抽离出属于自己特有的属性 public $playLength; function __construct( $title, $firstName, $mainName, $price, $playLength ) { parent::__construct( $title, $firstName, $mainName, $price ); // 继承父类的构造函数 $this->playLength = $playLength; // 处理自己专有的属性 } function getPlayLength() { return $this->playLength; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; $base .= ": playing time - {$this->playLength}"; return $base; } } class BookProduct extends ShopProduct { public $numPages; function __construct( $title, $firstName, $mainName, $price, $numPages ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->numPages = $numPages; } function getNumberOfPages() { return $this->numPages; } function getSummaryLine() { $base = "$this->title ( $this->producerMainName, "; $base .= "$this->producerFirstName )"; $base .= ": page count - $this->numPages"; return $base; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 ); print $product1->getSummaryLine(); print "\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); print $product2->getSummaryLine(); print "\n"; ?>
출력:
cd1(bobbleson, bob): 재생 시간 - 50
book1(harrelson, harry): 페이지 수 - 30
: 여기에 공통을 넣어 상위 클래스의 속성을 처리하고 자신의 클래스에서 다른 개별 속성을 처리합니다. 그리고 자신만의 생성 방법을 설정하고 상위 클래스의 생성 방법을 상속받습니다.
부모 클래스의 메서드를 추가로 상속
<?php class ShopProduct { public $title; public $producerMainName; public $producerFirstName; public $price; function __construct( $title, $firstName, $mainName, $price ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { public $playLength; function __construct( $title, $firstName, $mainName, $price, $playLength ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->playLength = $playLength; } function getPlayLength() { return $this->playLength; } function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": playing time - {$this->playLength}"; return $base; } } class BookProduct extends ShopProduct { public $numPages; function __construct( $title, $firstName, $mainName, $price, $numPages ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->numPages = $numPages; } function getNumberOfPages() { return $this->numPages; } function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": page count - {$this->numPages}"; return $base; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 ); print $product1->getSummaryLine(); print "\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); print $product2->getSummaryLine(); print "\n"; ?>
출력:
cd1(bobbleson, bob): 재생 시간 - 50
book1(harrelson, harry): 페이지 수 - 30
댓글: 동일한 결과를 최적화하고 다시 최적화할 수 있습니다. 여기서는 상위 클래스의 메소드가 상속됩니다. 부모::getSummaryLine(). 그러나 이는 덜 자주 사용됩니다.
흥미로운 콘텐츠를 계속 추가하세요
<?php class ShopProduct { private $title; private $discount = 0; private $producerMainName; private $producerFirstName; protected $price; function __construct( $title, $firstName, $mainName, $price ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } function setDiscount( $num ) { $this->discount=$num; } function getPrice() { return ($this->price - $this->discount); } function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { public $playLength; function __construct( $title, $firstName, $mainName, $price, $playLength ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->playLength = $playLength; } function getPlayLength() { return $this->playLength; } function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": playing time - {$this->playLength}"; return $base; } } class BookProduct extends ShopProduct { public $numPages; function __construct( $title, $firstName, $mainName, $price, $numPages ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->numPages = $numPages; } function getPrice() { return $this->price; } function getNumberOfPages() { return $this->numPages; } function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": page count - {$this->numPages}"; return $base; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 ); $product1->setDiscount( 3 ); print $product1->getSummaryLine(); print "\n"; print "price: {$product1->getPrice()}\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); $product2->setDiscount( 3 ); // 折扣对book无效 print $product2->getSummaryLine(); print "\n"; print "price: {$product2->getPrice()}\n"; ?>
출력:
cd1(bobbleson, bob): 재생 시간 - 50
가격: 1
book1(harrelson, harry): 페이지 수 - 30
price: 4
Comments: 부모 클래스에서 할인을 추가했습니다. 책이 상속된 후 getPrice 메소드가 수정되었으므로 책에는 할인이 적용되지 않습니다.
Private 속성, 메소드를 통한 설정 및 가져오기
<?php class ShopProduct { // 私有化属性,通过方法来设置与获取 private $title; private $producerMainName; private $producerFirstName; protected $price; private $discount = 0; public function __construct( $title, $firstName, $mainName, $price ) { $this->title = $title; $this->producerFirstName = $firstName; $this->producerMainName = $mainName; $this->price = $price; } public function getProducerFirstName() { return $this->producerFirstName; } public function getProducerMainName() { return $this->producerMainName; } public function setDiscount( $num ) { $this->discount=$num; } public function getDiscount() { return $this->discount; } public function getTitle() { return $this->title; } public function getPrice() { return ($this->price - $this->discount); } public function getProducer() { return "{$this->producerFirstName}". " {$this->producerMainName}"; } public function getSummaryLine() { $base = "{$this->title} ( {$this->producerMainName}, "; $base .= "{$this->producerFirstName} )"; return $base; } } class CdProduct extends ShopProduct { private $playLength = 0; public function __construct( $title, $firstName, $mainName, $price, $playLength ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->playLength = $playLength; } public function getPlayLength() { return $this->playLength; } public function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": playing time - {$this->playLength}"; return $base; } } class BookProduct extends ShopProduct { private $numPages = 0; public function __construct( $title, $firstName, $mainName, $price, $numPages ) { parent::__construct( $title, $firstName, $mainName, $price ); $this->numPages = $numPages; } public function getNumberOfPages() { return $this->numPages; } public function getSummaryLine() { $base = parent::getSummaryLine(); $base .= ": page count - {$this->numPages}"; return $base; } public function getPrice() { return $this->price; } } $product1 = new CdProduct("cd1", "bob", "bobbleson", 4, 50 ); print $product1->getSummaryLine()."\n"; $product2 = new BookProduct("book1", "harry", "harrelson", 4, 30 ); print $product2->getSummaryLine()."\n"; ?>
출력:
cd1(bobbleson, bob): 재생 시간 - 50
book1(harrelson, harry): 페이지 수 - 30
댓글: 여기에서 속성이 더욱 사유화되었으며 방법을 통해서만 얻을 수 있습니다. 이는 안전을 보장합니다.
위 내용은 이 글의 전체 내용이며, 모든 분들의 공부에 도움이 되었으면 좋겠습니다.
관련 추천:
위 내용은 PHP의 객체지향 상속 사용법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!