<?php
class String
{
public $value;
public function __construct($str=null)
{
$this->value = $str;
}
public function __call($name, $args)
{
$this->value = call_user_func($name, $this->value, $args[0]);
return $this;
}
public function strlen()
{
return strlen($this->value);
}
}
$str=new String('0121230');
echo $str->trim('0')->strlen();
关键点在于 return $this;返回调用后的对象
也可以这样
<?php
class String
{
public $value;
public function __construct($str=null)
{
$this->value = $str;
}
public function trim($t)
{
$this->value = trim($this->value, $t);
return $this;
}
public function strlen()
{
return strlen($this->value);
}
}
call_user_func():调用一个回调函数处理字符串,
可以用匿名函数,可以用有名函数,可以传递类的方法,
用有名函数时,只需传函数的名称
用类的方法时,要传类的名称和方法名
传递的第一个参数必须为函数名,或者匿名函数,或者方法
其他参数,可传一个参数,或者多个参数,这些参数会自动传递到回调函数中
而回调函数,可以通过传参,获取这些参数
返回回调函数处理后的结果
function callfunc($call){
//通过传参获取call_user_func传过来的参数
echo $call++.PHP_EOL;
echo $call++.PHP_EOL;
return $call;
}
//上面回调函数没有返回值,所以,这里就没有返回值,_call为上面的函数的名称
$re = call_user_func('callfunc',1);
var_dump($re);