2015-04-22 50 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