0

我试图让所选语言出现在与 function 的链接中buildMenu()

我想将它用作静态函数,以便可以在我的标题模板中调用它。如果我在函数中调用该函数,init()则一切正常,但是,当我尝试将其用作静态函数时,就没有任何作用了。我已经尝试了我所知道的一切,所以我对 php 的了解似乎到此为止了 :)

你们有任何提示吗?提前致谢!

class bootstrap {

    static public $lang;
    static public $class;
    static public $method;

    public function init(){
        $url = isset($_GET['url']) ? $_GET['url'] : null;
        $url = rtrim($url, '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);

        //Set values on startup
        if($url[0] == NULL) {$url[0] = 'nl';}
        if($url[1] == NULL) {$url[1] = 'index';}

        if(isset($url[0])) {$this->lang = $url[0];}
        if(isset($url[1])) {$this->class = $url[1];}
        if(isset($url[2])) {$this->method = $url[2];}        

        $this->loadClass();

    }

    public function loadClass(){

        $filename = 'libs/' . $this->class . '.php';
        if(file_exists($filename)){
            $newController = new $this->class($this->lang, $this->class, $this->method);
            $newView = new view($this->lang, $this->class, $this->method);
        } else {
            $newclass = new error($this->lang, $this->class, $this->method);
        }

    }


    public function buildMenu(){
        echo '<li><a href="http://localhost/testing/' . $this->lang . '/foto">Foto</a></li>';
    }

    /*
     * Set paths
     */

    public static function root(){
        echo "http://localhost/testing/";
    }

}
4

2 回答 2

1

您正在使用对象运算符( ->) 而不是用于引用类常量和静态属性或方法的范围解析运算符( )。::

有关 static 关键字和使用静态属性的说明,请参见此处

将您的代码更新为:

class bootstrap{

  static public $lang;
  static public $class;
  static public $method;

  public function init(){
    $url = isset($_GET['url']) ? $_GET['url'] : null;
    $url = rtrim($url, '/');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    $url = explode('/', $url);

    //Set values on startup
    if($url[0] == NULL) {$url[0] = 'nl';}
    if($url[1] == NULL) {$url[1] = 'index';}

    if(isset($url[0])) {self::$lang = $url[0];}
    if(isset($url[1])) {self::$class = $url[1];}
    if(isset($url[2])) {self::$method = $url[2];}       

    $this->loadClass();

  }

  public function loadClass(){

    $filename = 'libs/' . self::$class . '.php';
    if(file_exists($filename)){
        $newController = new self::$class(self::$lang, self::$class, self::$method);
        $newView = new view(self::$lang, self::$class, self::$method);
    } else {
        $newclass = new error(self::$lang, self::$class, self::$method);
    }

  }


  public static function buildMenu(){
        echo '<li><a href="http://localhost/testing/' . self::$lang . '/foto">Foto</a></li>';
  }

  public static function root(){
    echo "http://localhost/testing/";
  }
}
于 2013-09-21T22:19:01.940 回答
0

正如@elclanrs 已经提到的,如何将buildMenu()方法更改为

public static function buildMenu(){
    echo '<li><a href="http://localhost/testing/' . self::$lang . '/foto">Foto</a></li>';
}

然后,您可以使用bootstrap::buildMenu().

于 2013-09-21T22:19:00.267 回答