美文网首页
php中的可变函数

php中的可变函数

作者: 快乐的bug制造者 | 来源:发表于2018-04-27 11:47 被阅读13次

    这两天在写微信公众号支付和apple支付,其中项目中之前已经写好微信支付的回调了,初步想法是直接封装一下拿过来复用!!!但是结果是,我几乎花了一下午的时间才在回调中找到处理我们业务逻辑的入口~~~为什么呢?说出来很丢人,作为一个三年php开发者,居然看不懂php的可变函数!!!

    /**
         *
         * 回调入口
         * @param bool $needSign  是否需要签名输出
         */
        final public function Handle($needSign = true)
        {
            $msg = "OK";
            $result = WxpayApi::notify(array($this, 'NotifyCallBack'), $msg);//其中NotifyCallBack方法就是处理我们业务逻辑的入口
            if($result == false){
                $this->SetReturn_code("FAIL");
                $this->SetReturn_msg($msg);
                $this->ReplyNotify(false);
                return;
            } else {
                //该分支在成功回调到NotifyCallBack方法,处理完成之后流程
                $this->SetReturn_code("SUCCESS");
                $this->SetReturn_msg("OK");
            }
            $this->ReplyNotify($needSign);
        }
    

    其实就是对php可变函数的一种使用!简单聊下吧~~~

    可变函数示例:

    <?php
    function foo() {
        echo "In foo()<br />\n";
    }
    
    function bar($arg = '') {
        echo "In bar(); argument was '$arg'.<br />\n";
    }
    
    // 使用 echo 的包装函数
    function echoit($string)
    {
        echo $string;
    }
    
    $func = 'foo';
    $func();        // This calls foo()
    
    $func = 'bar';
    $func('test');  // This calls bar()
    
    $func = 'echoit';
    $func('test');  // This calls echoit()
    ?>
    

    也可以用可变函数的语法来调用一个对象的方法。

    <?php
    class Foo
    {
        function Variable()
        {
            $name = 'Bar';
            $this->$name(); // This calls the Bar() method
        }
    
        function Bar()
        {
            echo "This is Bar";
        }
    }
    
    $foo = new Foo();
    $funcname = "Variable";
    $foo->$funcname();   // This calls $foo->Variable()
    
    ?>
    

    当调用静态方法时,函数调用要比静态属性优先:

    <?php
    class Foo
    {
        static $variable = 'static property';
        static function Variable()
        {
            echo 'Method Variable called';
        }
    }
    
    echo Foo::$variable; // This prints 'static property'. It does need a $variable in this scope.
    $variable = "Variable";
    Foo::$variable();  // This calls $foo->Variable() reading $variable in this scope.
    
    ?>
    
    <?php
    class Foo
    {
        static function bar()
        {
            echo "bar\n";
        }
        function baz()
        {
            echo "baz\n";
        }
    }
    
    $func = array("Foo", "bar");
    $func(); // prints "bar"
    $func = array(new Foo, "baz");
    $func(); // prints "baz"
    $func = "Foo::bar";
    $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
    ?>
    

    相关文章

      网友评论

          本文标题:php中的可变函数

          本文链接:https://www.haomeiwen.com/subject/ynrblftx.html