PHP连接变量与常量

标签 php static constants

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

[17-Feb-2016 19:08:48 Europe/Berlin] PHP Warning: include(): Failed opening '/Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/template' for inclusion (include_path='.:/Applications/MAMP/bin/php/php7.0.0/lib/php') in /Applications/MAMP/htdocs/its_vegan/scripts/back_end/views/view.php on line 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;

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

最佳答案

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

template 指的是全局常量(例如通过 define('template', 'value');)

关于PHP连接变量与常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35464545/

相关文章:

php - php中如何将小数四舍五入到最接近的5或最接近的10

PHP 代码不允许通过我的表单发送多个输入值

firebase - Flutter FCM onBackgroundMessage 不适用于嵌套的非静态方法调用

java - 在java中设置静态对象

c++ - C++ 中带有 std::vector 的 const

c++ - 为什么 "auto const&"不是只读的?

php - 以编程方式监视网页

javascript - AJAX响应返回html内容

java - 创建数组的对象的静态数组。这是好是坏?

sql-server - SQL 中常量的最佳模式?