2016-02-17 24 views
1

我有一个静态的View类从另一个类传递一个字符串。当字符串作为变量传递时,它可以工作。当我将其更改为一个恒定的误差为:PHP连续变量与常量

[17-FEB-2016 19时08分48秒欧洲/柏林] PHP的警告:包括():无法 开口 “/应用/ MAMP/htdocs中/应用程序/ MAMP/bin/php/php7.0.0/lib/php'中的/in_vegan/ scripts/back_end/views/template' (include_path ='。:/ Applications/MAMP/bin/php'脚本/ back_end /视图/上 线view.php 23

class View { 

    /** 
    * ------------------------------------- 
    * Render a Template. 
    * ------------------------------------- 
    * 
    * @param $filePath - include path to the template. 
    * @param null $viewData - any data to be used within the template. 
    * @return string - 
    * 
    */ 
    public static function render($filePath, $viewData = null) { 

     // Was any data sent through? 
     ($viewData) ? extract($viewData) : null; 

     ob_start(); 
     include ($filePath);// error on this line 
     $template = ob_get_contents(); 
     ob_end_clean(); 

     return $template; 
    } 
} 

class CountrySelect { 

    const template = 'select_template.php'; //the const is template 

    public static function display() { 

     if (class_exists('View')) { 

      // Get the full path to the template file. 

      $templatePath = dirname(__FILE__) . '/' . template; //the const is template 

      $viewData = array(
       "options" => '_countries', 
       "optionsText" => 'name', 
       "optionsValue" => 'geonameId', 
       "value" => 'selectedCountry', 
       "caption" => 'Country' 
      ); 

      // Return the rendered HTML 
      return View::render($templatePath, $viewData); 

     } 
     else { 
      return "You are trying to render a template, but we can't find the View Class"; 
     } 
    } 
} 

在CountrySelect中做了什么工作:

$templatePath = dirname(__FILE__) . '/' . static::$template; 

为什么模板必须是静态的?我可以使它成为一个静态常量吗?

+0

您需要参考其使用'自:: constname' – PeeHaa

+0

访问通过双冒号'做一流的常量::'运营商。 (AKA示波器解析运算符)。如果'static'关键字困扰你,那么另一个选择就是'self'。关于该主题的[文档可以略述](http://php.net/manual/en/language.oop5.late-static-bindings.php)。 – Crackertastic

回答

2

在这条线

$templatePath = dirname(__FILE__) . '/' . template; 

template不是恒定的,因为里面声明类常量template。此代码的工作原理类似于

$templatePath = dirname(__FILE__) . '/template'; 

因此,使用static::template

+0

不是我的downvote,但OP的代码显示为'const template ='select_template.php'; // const是模板'并且看起来超出了范围。 –

+0

哦,是的。编辑) – mnv

+1

现在,“upvote”是我的;-) *只是说'* –