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', 'johndoe@mail.com');
//$customer2 = new Customer(null, 'Mary', 'Poppins', 'mp@mail.com');
$customer3 = new Premium(7, 'James', 'Bond', '007@mail.com');
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.
php的类使用样例的更多相关文章
- Scala模式匹配和样例类
Scala有一个十分强大的模式匹配机制,可以应用到很多场合:如switch语句.类型检查等.并且Scala还提供了样例类,对模式匹配进行了优化,可以快速进行匹配. 1.字符匹配 def mai ...
- OpenCV LDA(Linnear Discriminant analysis)类的使用---OpenCV LDA演示样例
1.OpenCV中LDA类的声明 //contrib.hpp class CV_EXPORTS LDA { public: // Initializes a LDA with num_componen ...
- 【Scala篇】--Scala中Trait、模式匹配、样例类、Actor模型
一.前述 Scala Trait(特征) 相当于 Java 的接口,实际上它比接口还功能强大. 模式匹配机制相当于java中的switch-case. 使用了case关键字的类定义就是样例类(case ...
- Scala--模式匹配和样例类
模式匹配应用场景:switch语句,类型查询,析构,样例类 一.更好的switch val ch :Char = '+' val sign = ch match{ case '+' => 1 c ...
- Scala-Unit6-final/type关键字、样例类&样例对象
一.关键字 1.final关键字 用final修饰的类:不能被继承 用final修饰的方法:不能被重写 注意:(1)在Scala中变量不需要用final修饰,因为val与var已经限制了变量是否可变 ...
- Scala基础:模式匹配和样例类
模式匹配 package com.zy.scala import scala.util.Random /** * 模式匹配 */ object CaseDemo { def main(args: Ar ...
- Java线程演示样例 - 继承Thread类和实现Runnable接口
进程(Process)和线程(Thread)是程序执行的两个基本单元. Java并发编程很多其它的是和线程相关. 进程 进程是一个独立的执行单元,可将其视为一个程序或应用.然而,一个程序内部同事还包括 ...
- Scala学习十四——模式匹配和样例类
一.本章要点 match表达式是更好的switch,不会有意外调入下一个分支 如果没有模式能够匹配,会抛出MatchError,可以用case _模式避免 模式可以包含一个随意定义的条件,称做守卫 你 ...
- 学好Spark/Kafka必须要掌握的Scala技术点(二)类、单例/伴生对象、继承和trait,模式匹配、样例类(case class)
3. 类.对象.继承和trait 3.1 类 3.1.1 类的定义 Scala中,可以在类中定义类.以在函数中定义函数.可以在类中定义object:可以在函数中定义类,类成员的缺省访问级别是:publ ...
随机推荐
- 获取最新的中国IP的脚本,给ROS可以使用的脚本
wget http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latestecho "/ip firewall address-li ...
- java web开发入门一(servlet和jsp)基于eclispe
servlet 用java语言开发动态资源网站的技术,在doGet方法中拼接显示html,在doPost方法中提交数据.类似于.net的ashx技术. servlet生成的class文件存放在tomc ...
- html中利用flex容器书写的布局样式
首先页面基本样式见下图: 如有兴趣可以打开https://migloo.gitee.io/front 或者 https://www.igloo.xin/front 进行查看
- 利用ffmpeg获取视频帧
如果要对视频帧进行处理,可以先把视频帧读取出来. sh文件代码如下: #!/usr/bin/env sh VIDEO=/home/xxx/video/ FRAMES=/home/xxx/frame/ ...
- 《Linux就该这么学》培训笔记_ch18_使用MariaDB数据库管理系统
<Linux就该这么学>培训笔记_ch18_使用MariaDB数据库管理系统 文章最后会post上书本的笔记照片. 文章主要内容: 初始化MariaDB服务 管理用户以及授权 创建数据库与 ...
- AntDesign vue学习笔记(五)导航菜单动态加载
一般的后台系统都有一个树形导航菜单,具体实现如下,主要参考https://my.oschina.net/u/4131669/blog/3048416 "menuList": [ { ...
- golang gin 上传图片到aws s3
要上传图片到aws s3首先需要 知道 aws 的地区 也就是region ,还需要知道储存桶的名字,其次就是Access key ID和Secret access key package handl ...
- 中级java面试经历
2018年已经远去,2019年悄然而至.跳槽不仅是为了涨薪,更是为了锻炼自己,提高自己的能力.树挪死,人挪活.在一个公司呆的时间越长,就越老油条,从而失去不断前进的动力.现在下面就主要讲述我这一个月面 ...
- Java-关于接口调用的处理
前言:这是我的第一篇博文,是我对现在一些接口调用的梳理,写的不好,请见谅. 序:接口无非就是“你调用别人的接口”和“别人调用你的接口”,我会对这两种情况分别的理一下我的思路. 准备:我使用的是Http ...
- excel查找定位操作(for lutai)
产成品出库的单价要根据订单号和存货编码引用产成品入库的单价 方法一:使用Index 和Match =INDEX(产成品入库!I2:P13 ,IF( ) ,7) 方法二:使用vlookup ,首先 ...