__call和__callStatic无法正常工作或写错

时间:2015-04-22 23:10:02

标签: php call construct

<?php
    class Statics {

        private static $keyword;

        public static function __callStatic($name,$args){
            self::$keyword = "google";
        }
        public static function TellMe(){
            echo self::$keyword;
        }
    }

    Statics::TellMe();

这是我尝试使用__construct的简单细分,但是我编写代码Statics::TellMe();的方式我需要为new编写__construct才能正常工作。而我的私有静态变量keyword如果没有被称为为什么这不起作用的任何想法都不会被写入?

IDE Not Working Example

    private static $pathname;
    public function __construct($dir = "")
    {
        set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
        if($dir !== "") {
            $dir = "/".$dir;
        }
        self::$pathname = $dir.".htaccess"; 
        if( file_exists(self::$pathname) ) {
            self::$htaccess = file_get_contents($dir.".htaccess",true);
            self::$htaccess_array = explode("\n",self::$htaccess);
        }
    }

self::$patname未被分配,因为我没有$key = new Key();,所以如果我只是Key::get()或类似的话,我需要一种方法来实现。

1 个答案:

答案 0 :(得分:1)

你对__callStatic的工作方式确实存在误解。 当静态方法对类不可知时,魔术方法__callStatic将作为回退方法。

class Statics {

    private static $keyword;

    public static function __callStatic($name,$args){
        return 'I am '.$name.' and I am called with the arguments : '.implode(','$args); 
    }
    public static function TellMe(){
        return 'I am TellMe';
    }
}

echo Statics::TellMe(); // print I am TellMe
echo Statics::TellThem(); // print I am TellThem and I am called with the arguments : 
echo Statics::TellEveryOne('I','love','them'); // print I am TellEveryOne and I am called with the arguments : I, love, them

所以在你的情况下你可以做的是:

class Statics {

    private static $keyword;

    public static function __callStatic($name,$args){
        self::$keyword = "google";
        return self::$keyword;
    }
}

echo Statics::TellMe();

根据你的编辑:

class Statics{
    private static $pathname;
    private static $dir;

    public function getPathName($dir = "")
    // OR public function getPathName($dir = null) 
    {
        if($dir !== self::$dir || self::$pathname === ''){
        // OR if($dir !== null || self::$pathname === ''){ -> this way if you do getPathName() a second time, you don't have to pass the param $dir again
            self::$dir = $dir;
            set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
            if($dir !== "") {
                $dir = "/".$dir;
            }
            self::$pathname = $dir.".htaccess"; 
            if( file_exists(self::$pathname) ) {
                self::$htaccess = file_get_contents($dir.".htaccess",true);
                self::$htaccess_array = explode("\n",self::$htaccess);
            }
        }
        return self::$pathname;
    }
}

echo Statics::getPathName('some');