2015-04-22 52 views
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不会被写入没有被称为任何想法,为什么这是行不通的?__call和__callStatic不能正常工作或写入错误

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()或类似的东西。

+0

错误是告诉你什么是错的:__callStatic应该被声明为public静态__callStatic –

+1

好吧大声笑我会尝试出来认为它也必须是一个功能-_- – EasyBB

+0

仍然不能正常工作-_-唉这样的背后疼痛 – EasyBB

回答

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'); 
+0

这只是一个普遍的情况下,试图让'self :: $关键字'被创建。我会更新我的代码实际上看起来像'__construct'方法 – EasyBB

+0

是的,但是你不能在PHP中构造一个静态类。然后你必须像在我的编辑中一样工作,或者首先使用':: init()静态函数来运行' –

+0

我会看看我能做什么,可能只需要初始化它。谢谢@ b.enoit.be – EasyBB