php的类使用样例

这个demo。差不多php的类的主要知识点都用到了。

public,private关键字,

namespace,use命令空间,

require导入,

interface复用,

abstract抽象类,

trait代码复用

static静态变量及静态方法

extends继承

implements实现

__construct初始化

=====================

Unique.php

<?php
namespace Bookstore\Utils;

trait Unique {
    //static静态属性,类似于其它语言的类变量
    private static $lastId = 0;
    //protected保护属性,仅允许继承类访问
    protected $id;
    
    public function setId(int $id) {
        //内置函数判断id是否为空,比$id == null要逼格好点
        if (empty($id)) {
            //注意区分$this-和self::$的语法
            $this->id = ++self::$lastId;
        } else {
            $this->id = $id;
            if ($id > self::$lastId) {
                self::$lastId = $id;
            }
        }
    }
    
    public function getId():int {
        return $this->id;
    }
    
    //静态方法
    public static function getLastId():int {
        return self::$lastId;
    }
    
    
}

?>

Person.php

<?php
namespace Bookstore\Domain;
use Bookstore\Utils\Unique;

//命名空间可以直接use,但如果这个命名空间没有在标准约定位置,且没有自动载入的话,需要使用require来手工定位一下.
require_once __DIR__ . '/Unique.php';

class Person {
    //trait的用法,类内use
    use Unique;
    //protected保护属性,仅允许继承类访问
    protected $firstname;
    protected $surname;
    //private私有属性,不允许类外部直接修改
    private $email;


    //构造函数,初始化类的好地方
    public function __construct(
        $id,
        string $firstname,
        string $surname,
        string $email
    ) {
        $this->firstname = $firstname;
        $this->surname = $surname;
        $this->email = $email;
        //复用trait内的方法代码
        $this->setId($id);
    }
    
    public function getFirstname():string {
        return $this->firstname;
    }
    
    public function getSurname():string {
        return $this->surname;
    }
    
    public function getEmail():string {
        return $this->email;
    }
    //类的部通过public方法更改属性,达到信息封装;类内部通过->修改.
    public function setEmail(string $email) {
        $this->email = $email;
    }
}
?>

Payer.php

<?php
//命名空间
namespace Bookstore\Domain;

interface Payer {
    public function pay(float $amount);
    public function isExtentOfTaxes(): bool;
}
?>

Customer.php

<?php
//命名空间
namespace Bookstore\Domain;

//use Bookstore\Domain\Payer;

require_once __DIR__ . '/Payer.php';

interface Customer {
    public function getMonthlyFee(): float;
    public function getAmountToBorrow(): int;
    public function getType(): string;
}
?>

Basic.php

<?php
namespace Bookstore\Domain;
/*
use Bookstore\Domain\Person;
use Bookstore\Domain\Customer;
use Bookstore\Domain\Payer;
*/

require_once __DIR__ . '/Person.php';
require_once __DIR__ . '/Customer.php';
require_once __DIR__ . '/Payer.php';


class Basic extends Person implements Customer, Payer {
    public function getMonthlyFee():float {
        return 5.0;
    }
    public function getAmountToBorrow():int {
        return 3;
    }
    public function getType(): string {
        return 'Basic';
    }
    
    public function pay(float $amount) {
        echo "Paying $amount.";
    }
    
    public function isExtentOfTaxes(): bool {
        return false;
    }
}
?>

Premium.php

<?php
namespace Bookstore\Domain;

/*
use Bookstore\Domain\Person;
use Bookstore\Domain\Customer;
use Bookstore\Domain\Payer;
*/

require_once __DIR__ . '/Person.php';
require_once __DIR__ . '/Customer.php';
require_once __DIR__ . '/Payer.php';

class Premium extends Person implements Customer, Payer {
    public function getMonthlyFee():float {
        return 10.0;
    }
    public function getAmountToBorrow():int {
        return 10;
    }
    public function getType(): string {
        return 'Premium';
    }
    
    public function pay(float $amount) {
        echo "Paying $amount.";
    }
    
    public function isExtentOfTaxes(): bool {
        return true;
    }
}
?>

Book.php

<?php
namespace Bookstor\Domain;

class Book {
    public function __construct (
        int $isbn,
        string $title,
        string $author,
        int $available = 0
    ) {
        $this->isbn = $isbn;
        $this->title = $title;
        $this->author = $author;
        $this->available = $available;
    }
    
    public function getIsbn():int {
        return $this->isbn;
    }
    
    public function getTitle():string {
        return $this->title;
    }
    
    public function getAuthor():string {
        return $this->author;
    }
    
    public function isAvailable():bool {
        return $this->available;
    }
    
    public function getCopy():bool {
        if ($this->available < 1) {
            return false;
        } else {
            $this->available--;
            return true;
        }
    }
    
    public function addCopy() {
        $this->available++;
    }
    
    public function __toString() {
        $result = '<i>' . $this->title . '</i> - ' . $this->author;
        if (!$this->available) {
            $result .= ' <b>Not available</b>';
        } else {
            $result .= " <b>{$this->available}</b>";
        }
        return $result . '<br/>';
    }
}
?>

test.php

<?php
//使用命名空间,易于在大型应用中管理和组织php类.
use Bookstor\Domain\Book;
use Bookstore\Domain\Customer;
use Bookstore\Domain\Person;
use Bookstore\Domain\Basic;
use Bookstore\Domain\Premium;
use Bookstore\Utils\Unique;

//命名空间可以直接use,但如果这个命名空间没有在标准约定位置,且没有自动载入的话,需要使用require来手工定位一下.
require_once __DIR__ . '/Unique.php';
require_once __DIR__ . '/Book.php';
require_once __DIR__ . '/Customer.php';
require_once __DIR__ . '/Person.php';
require_once __DIR__ . '/Basic.php';
require_once __DIR__ . '/Premium.php';


$book1 = new Book("1984", "George Orwell", 9785267006323, 12);
$book2 = new Book("1984", "George Orwell", 9785267006323);

$customer1 = new Basic(5, 'John', 'Doe', '[email protected]');
//$customer2 = new Customer(null, 'Mary', 'Poppins', '[email protected]');
$customer3 = new Premium(7, 'James', 'Bond', '[email protected]');

if ($book1->getCopy()) {
    echo 'Sale 1 copy.<br/>';
} else {
    echo 'can not sale.<br/>';
}
//数据类型转换,天下语言几乎大同.
$string1 = (string)$book1;
$string2 = (string)$book2;
echo $string1;
echo $string2;
//调用类的静态方法,可以直接用类名,也可以用实例名.但都是用::符号.
echo Person::getLastId();
echo '<br/>';
echo $customer1::getLastId();

function checkIfValid(Customer $customer, array $books):bool {
    return $customer->getAmountToBorrow() >= count($books);
}
echo '<br/>';
var_dump(checkIfValid($customer1, [$book1]));
echo '<br/>';
var_dump(checkIfValid($customer3, [$book1]));
echo '<br/>';
$basic = new Basic(1, "name", "surname", "email");
$premium = new Premium(2, "name", "surname", "email");
var_dump($basic->getId());
echo '<br/>';
var_dump($premium->getId());
echo '<br/>';
var_dump(Person::getLastId());
echo '<br/>';
var_dump(Unique::getLastId());
echo '<br/>';
var_dump(Basic::getLastId());
echo '<br/>';
var_dump(Premium::getLastId());
echo '<br/>';
//判断父类及继承关系
var_dump($basic instanceof Basic);
echo '<br/>';
var_dump($premium instanceof Basic);
echo '<br/>';
var_dump($basic instanceof Customer);
echo '<br/>';
var_dump($premium instanceof Payer);
echo '<br/>';
var_dump($basic instanceof Payer);
echo '<br/>';

function processPayment($payer, float $amount) {
    if ($payer->isExtentOfTaxes()) {
        echo "What a lucky one...";
    } else {
        $amount *= 1.16;
    }
    $payer->pay($amount);
}

//多态实现
processPayment($basic, 2000);
echo '<br/>';
processPayment($premium, 2000);
echo '<br/>';

    
?>

输出:

Sale 1 copy.
George Orwell - 9785267006323 11
George Orwell - 9785267006323 Not available
7
7
bool(true) 
bool(true) 
int(1) 
int(2) 
int(7) 
int(0) 
int(7) 
int(7) 
bool(true) 
bool(false) 
bool(true) 
bool(false) 
bool(false) 
Paying 2320.
What a lucky one...Paying 2000.

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11127865.html
今日推荐