簡體   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