I have a static View
class that gets passed a string from another class. When the string is passed through as a variable it works. When I change it to a constant the error is:
[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";
}
}
}
What did work was having this in the CountrySelect:
$templatePath = dirname( __FILE__ ) . '/' . static::$template;
Why does the template have to be static? Can I make it a static constant?
You could also use self::template
Since class constants are defined at a per class level instead of per-object, static::template
will refer to the same, unless you have a child class. (See https://secure.php.net/manual/en/language.oop5.late-static-bindings.php )
template
refers to a global constant (eg by define('template', 'value');
)
At this line
$templatePath = dirname( __FILE__ ) . '/' . template;
template
is not constant, because constant template
declared inside class. This code works similar
$templatePath = dirname( __FILE__ ) . '/template';
so, use static::template
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.