繁体   English   中英

PHP将变量与常量连接

[英]PHP concatenate variable with constant

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

[2016年2月17日19:08:48欧洲/柏林] PHP警告:include():无法打开要包含在内的'/ Applications / MAMP / htdocs / its_vegan / scripts / back_end / views / template'(include_path ='。:第23行的/Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/view.php中的/Applications/MAMP/bin/php/php7.0.0/lib/php')

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;

为什么模板必须是静态的? 我可以将其设为静态常数吗?

您也可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM