PHP几个常见不常用的方法

method_exists判断方法是否存在

<?php

class F{
    public function __construct(){
        if(method_exists($this, 'son_fun1')){
            echo 'son_fun1存在';
        }else{
            echo 'son_fun1不存在';
        }
        if(method_exists($this,'son_fun2')){
            echo 'son_fun2存在';
        }else{
            echo 'son_fun2不存在';
        }
    }
}
class S extends F{
    public function son_fun1(){
    }
}
$a = new S();

call_user_func 动态传入函数方法名

<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

// You can use this instead
call_user_func_array('increment', array(&$a));//要被传入回调函数的数组得是索引数组。
echo $a."\n";

 register_shutdown_function当PHP脚本发生致命错误时调用的方法

<?php
 
    //禁止错误输出
    error_reporting(0);
    //设置错误处理器
    set_error_handler('errorHandler');
    register_shutdown_function('fatalErrorHandler');
    class Test{
            public function index(){
                    //这里发生一个警告错误,出发errorHandler 
                    echo $undefinedVarible;
            }
    }
    function errorHandler($errno,$errstr,$errfile,$errline){
             $arr = array(
                            '['.date('Y-m-d h-i-s').']',
                            'http://www.baidu.com',
                            '|',
                            $errstr,
                            $errfile,
                            'line:'.$errline,
                        );
             //写入错误日志
                         //格式 :  时间 uri | 错误消息 文件位置 第几行
             error_log(implode(' ',$arr)."\r\n",3,'./test.txt','extra');
             echo implode(' ',$arr)."\r\n";
    }
 
    //捕获fatalError
    function fatalErrorHandler(){
             $e = error_get_last();
             switch($e['type']){
                case E_ERROR:
                case E_PARSE:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                     errorHandler($e['type'],$e['message'],$e['file'],$e['line']);
                     break;         
            }
    }
    $test = new Test();
    ////这里发生一个警告错误,被errorHandler 捕获
    $test->index();
    //发生致命错误,脚本停止运行触发 fatalErrorHandler 
    $test = new Tesdt();
    $test->index();

  trigger_error() 函数创建用户级别的错误消息。

<?php
 if ($usernum>10) {
     trigger_error("Number cannot be larger than 10");//Notice: Number cannot be larger than 10 in C:\webfolder\test.php on line 6
} ?>

  __set __get __call __callstatic __isset __unset 几个魔术方法

__set():为私有成员属性设置值的,在对象中设置一个不存在的属性时,会被调用
__get()方法:获取私有成员属性值的,在对象中调用一个不存在的属性时,会被调用
__call():监视一个对象中的其它方法,在对象中调用一个不可访问方法时,会被调用
__callstatic():监视一个对象中的其它静态方法,在对象中调用一个不可访问静态方法时,会被调用
__isset() :当 用isset() 判断对象不可见的属性时(protected/private/不存在的属性)  
会引发 __isset()来执行  
__unset():当 用unset 销毁对象的不可见属性时,  会引发 __unset();  

  

posted @ 2017-06-21 19:53  雨落知音  阅读(483)  评论(0编辑  收藏  举报