php function bind object

最近在看一些偏门的PHP语法程序,发现一个神奇的东西,独立的函数中只要声明了绑定对象,就可以使用对象的方法和属性,就好像这个函数本身就存在于这个对象当中。话不多说,上代码

在PHP7之前使用

<?php

class Test{
	
	public $name,$age;
	
	public function __construct($attributes)
	{
		$this->name = $attributes['name'];
		$this->age = $attributes['age'];
	}
}

$func = function($prefix = '__'){
	return $prefix . 'name:' . $this->name;
};

$data = [
	'name'	=>	'谭勇',
	'age'	=>	27
];

$test = $func->bindTo(new Test($data));

echo $test();//输出结果  __name:谭勇
?>

当Class Test属性$name 声明为private或是protected时,上述程序运行会报错。如需执行成功需修改为如下代码

<?php

class Test{
	
	private $name,$age;
	
	public function __construct($attributes)
	{
		$this->name = $attributes['name'];
		$this->age = $attributes['age'];
	}
}

$func = function($prefix = '__'){
	return $prefix . 'name:' . $this->name;
};

$data = [
	'name'	=>	'谭勇',
	'age'	=>	27
];

//将类名声明在第二个参数上即可正常运行
$test = $func->bindTo(new Test($data),'Test');

echo $test();//输出结果  __name:谭勇
?>

PHP7的新特性之一简化了这个步骤代码如下所示


class Test{
	
	private $name,$age;
	
	public function __construct($attributes)
	{
		$this->name = $attributes['name'];
		$this->age = $attributes['age'];
	}
}

$func = function($prefix = '__'){
	return $prefix . 'name:' . $this->name;
};

$data = [
	'name'	=>	'谭勇',
	'age'	=>	27
];

//php7新特性,在call绑定此对象时,就已经执行了一次,而不像之前的版本需要手动调用
echo $test->call(new Test($data));

具体原理参见其它博主说明点击查看详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值