Blogger Information
Blog 33
fans 0
comment 0
visits 20690
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的魔术方法和静态方法的定义和访问-2018年9月7日
马聪 15558002279的博客
Original
588 people have browsed it
  1. 利用__callStatic()魔术方法和call_user_func_array()模仿tp框架的链式查询;

     

     
  2. 实例

    <?php
    class Conn{
    	private $pdo = null;
    		private $config = [
    		'type'=>'mysql',
    		'host'=>'localhost',
    		'user'=>'abc',
    		'pwd'=>'abc',
    		'db_name'=>'test',
    	];
    	private $talbe;
    	private $field;
    	private $where;
    	function __construct(){
    		$this->pdo = new PDO("mysql:host=localhost;dbname=test",$this->config['host'],'abc');
    	}
    	//连接数据结束
    	public function table($table){
    		$this->table = $table;
    		//返回对象本身
    		return $this;
    	}
    	public function field($field){
    		$this->field = $field;
    		return $this;
    	}
    	public function where($where){
    		$this->where = $where;
    		return $this;
    	}
    	public function select(){
    		$sql = "SELECT $this->field FROM `{$this->table}` WHERE {$this->where}";
    		echo $sql;
    		$stmt = $this->pdo->prepare($sql);
    		$stmt->execute();
    		return $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
    	}
    
    }
    
    
    
    class Db{
    	public static function __callStatic($name,$value){
    		//调用Conn对象处理table()并返回最后结果
    		return call_user_func_array([(new Conn()),$name], $value);
    	}
    }
    
    // DB::table('user')->field('id,name,pwd')->where('id=2')->select();
    $res = Db::table('user')->field('id,name,pwd')->where('id=2')->select();
    echo "id为",$res['id'],'姓名',$res['name'],'密码',$res['pwd'];
    ?>

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

  3. 后期静态绑定的原理与使用场景分析:

    父类和子类都定义了相同名字“FN”的静态方法。父类中有一静态方法使用self::FN()调用了这个方法,当实例化子类并调用self::FN()的时候,程序不知道用户到底想调用哪个,只会一直调用父类中的FN()。
    父类方法中self::fn() => static::fn()  这样就能够自动识别是要执行子类的还是父类的。
    static 谁调用就绑定为谁
Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post