作业一:单例模式
1、代码:
<?php
namespace mode;
class Single
{
private static $mysql=null;
private function __construct(...$linkParams)
{
list($dsn,$username,$password)=$linkParams;
self::$mysql=new \PDO($dsn,$username,$password);
}
private function __clone()
{
// …………
}
public static function getnew(...$linkParams)
{
if (is_null(self::$mysql)) {
new self(...$linkParams);
}
return self::$mysql;
}
}
$link=['mysql:host=NewYear.com;dbname=php','phptest','123456'];
$mysql=Single::getnew(...$link);
$my=Single::getnew(...$link);
var_dump($mysql===$my);
echo '<pre>'.print_r($mysql->query('select * from `staffs`')->fetchAll(\PDO::FETCH_ASSOC),true).'</pre>';
运行结果图:
作业二:工厂模式(抽象类)工厂类是把多个类的实例化集中到一个类中,本质没有变;
1、目录结构:
2、Minus.php代码:
<?php
namespace base\method;
class Minus
{
public $num1;
public $num2;
public function __construct($num1,$num2)
{
$this->num1=$num1;
$this->num2=$num2;
}
public function get_result()
{
$c = $this->num1 - $this->num2;
return '相减结果是:'.$c;
}
}
3、Plus.php代码:
<?php
namespace base\method1;
class Plus implements Post
{
public $num1;
public $num2;
public function __construct($num1,$num2)
{
$this->num1=$num1;
$this->num2=$num2;
}
public function get_result()
{
$c = $this->num1 + $this->num2;
return '相加结果是:'.$c;
}
}
// $plus=new Plus(1,2);
// echo $plus->get_result();
4、Ride.php代码:
<?php
namespace base\method1;
class Ride implements Post
{
public $num1;
public $num2;
public function __construct($num1,$num2)
{
$this->num1=$num1;
$this->num2=$num2;
}
public function get_result()
{
$c = $this->num1 * $this->num2;
return '相乘结果是:'.$c;
}
}
5、Post.php代码:
<?php
namespace base\method1;
interface Post
{
public function get_result();
}
6、demo3.php代码:
<?php
namespace part1;
use base\method1\Minus;
use base\method1\Plus;
use base\method1\Ride;
use base\method1\Post;
require __DIR__.DIRECTORY_SEPARATOR.'autoload.php';
class Count1
{
public function yunsuan(Post $class)
{
return $class->get_result();
}
}
echo (new Count1())->yunsuan(new Plus(1,2)) . '<br>';
echo (new Count1())->yunsuan(new Minus(4,5)) . '<br>';
echo (new Count1())->yunsuan(new Ride(3,9)) . '<br>';
6、运行结果图:
作业三:知识点总结:
1、clone
:复制关键字(对象);$new=new Mysql();$s=clone $new;
2、__clone()
;复制对象实列,无法直接备调用;
3、通过私有化(private)__construct()
和__clone()
来禁止类实列化和复制;
4、spl_autoload_register()
:自动加载器(闭包);
5、__DIR__
和dirname()
区别:__DIR__
和dirname(__FILE__)
功能一致;
6、require 'demo.php';
加载关键字:require
7、接口类关键字interface:interface Post{}
8、继承接口类关键字implements:class Mode implements Post{};
9、类继承关键字:extends
10、抽象类和方法关键字:abstract 继承抽象类的关键字:extends