1
<?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 不工作示例

    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()或类似的事情,我需要一种方法来做到这一点。

4

1 回答 1

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');
于 2015-04-22T23:50:32.963 回答