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

__call and __callStatic not working properly or writing incorrectly

<?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() 或类似的事情。

你确实对__callStatic的工作方式有误解。 当 class.

不知道静态方法时,魔术方法 __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');