PHP 将变量与常量连接起来


PHP concatenate variable with constant

我有一个静态View类,它从另一个类传递了一个字符串。当字符串作为变量传递时,它会起作用。当我将其更改为常量时,错误是:

[17-Feb-2016 19:08:48 欧洲/柏林] PHP 警告: include(): 失败 开放 '/Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/template' 供收录 (include_path='.:/Applications/MAMP/bin/php/php7.0.0/lib/php') in /Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/view.php on 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";
        }
    }
}

在国家选择中有什么工作:

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

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

你也可以

使用self::template
由于类常量是在每个类级别而不是每个对象定义的,因此static::template将引用相同的内容,除非您有一个子类。 (见 https://secure.php.net/manual/en/language.oop5.late-static-bindings.php)

template是指全局常数(例如define('template', 'value');

在此行

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

template不是常量,因为常量template类中声明的。此代码的工作方式类似

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

因此,请使用static::template