PHP конкатенировать переменную с константой

У меня есть статический класс View, которому передается строка из другого класса. Когда строка передается как переменная, она работает. Когда я меняю его на константу, ошибка:

[17-Feb-2016 19:08:48 Europe/Berlin] Предупреждение PHP: include(): не удалось открыть '/Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/template' для включения (include_path='.: /Applications/MAMP/bin/php/php7.0.0/lib/php') в /Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/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;

Почему шаблон должен быть статичным? Могу ли я сделать его статической константой?


person BeniaminoBaggins    schedule 17.02.2016    source источник
comment
Вам нужно сослаться на него, используя self::constname   -  person PeeHaa    schedule 17.02.2016
comment
Доступ к константам класса осуществляется с помощью оператора :: с двойным двоеточием. (оператор разрешения области действия). Если вас беспокоит ключевое слово static, альтернативой является self. документация может пролить свет на эту тему.   -  person Crackertastic    schedule 17.02.2016


Ответы (2)


На этой линии

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

template не является константой, потому что константа template объявлена ​​внутри класса. Этот код работает аналогично

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

поэтому используйте static::template

person Nick    schedule 17.02.2016
comment
Не мое отрицательное мнение, но код OP отображается как const template = 'select_template.php'; //the const is template и кажется невозможным. - person Funk Forty Niner; 17.02.2016
comment
тот, кто проголосовал против, теперь должен отказаться. Это было бы благородным поступком. - person Funk Forty Niner; 17.02.2016

Вы также можете использовать self::template
Поскольку константы класса определяются на уровне класса, а не на уровне объекта, static::template будет ссылаться на то же самое, если у вас нет дочернего класса. (См. https://secure.php.net/manual/en/language.oop5.late-static-bindings.php)

template относится к глобальной константе (например, define('template', 'value');)

person WhoIsJohnDoe    schedule 17.02.2016