Blogger Information
Blog 31
fans 0
comment 0
visits 24383
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Day36-2018/1/11(完成 __call(),__callStatic()二个方法跨类调用)
SmallKing的博客
Original
657 people have browsed it

内容:完成 __call(),__callStatic()二个方法跨类调用,使用call_user_func_array()函数实现

为了方便2个类写在一个php文件里面

<?php
class person //人
{
    protected $name; //姓名
    private $age;//年龄
    private $sex;//性别
    public function __set($name,$value)//设置保护或私有属性
    {
        if($name=='age') {
            if ($value>0&&$value<120) {
                $this->age=$value;
            }else {echo  '非法输入年龄:'.$value;
                return; }
        }
        if($name=='sex') {
            if ($value=='男'||$value=='女') {
                $this->sex=$value;
            }else {echo  '请输入"男"或"女",性别不能为"'.$value.'"';
                return; }
        }

        $this->$name=$value;
    }
    public function __get($name)//获取商品信息
    {
        return $this->$name;
    }
    public function printInfo($name,$age,$sex){
        return "姓名:{$name}<br>年龄:{$age}<br>性别:{$sex}<br>__call()调用<hr>";
    }
    public static function staticPrintInfo($name,$age,$sex){
        echo "姓名:{$name}<br>年龄:{$age}<br>性别:{$sex}<br>__callStatic()调用<hr>";
    }
}
//require "demo.php";为了方便写在一个php文件里面
class person2{
    //调用person类里面的非静态方法
    public function __call($name, $arguments)
    {
        return call_user_func_array([(new person()),$name],$arguments);
    }
    //调用静态方法'staticPrintInfo
    public static function __callStatic($name, $arguments)
    {
       return call_user_func_array('staticPrintInfo',$arguments);
    }

}
echo (new person2)->printInfo('小王','20','男');
echo (new person2)->staticPrintInfo('小红','18','女');



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