You cannot have code "outside" of a method in a class. e.g.
class foo {
if (true) { ... }; <---bad code
function bar() {
if (true) { ... } <-- ok code
}
}
Frage
I want to include this if condition inside my code :
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
// Do something
}
I want to trigger a part of my code only when this condition is true, so my entire code is looking like this :
<?php
abstract class ECF_Field_Type {
private static $types = array();
protected $name;
/* Constructor */
public function __construct() {
self::register_type( $this->name, $this );
}
/* Add a type to the types list */
private static function register_type( $name, $type ) {
self::$types[$name] = $type;
}
/* Return the appropriate type */
public static function get_type( $name ) {
return array_key_exists( $name, self::$types )
? self::$types[$name] : self::get_default_type();
}
/* Return all types */
public static function get_types() {
return self::$types;
}
/* Get default type */
public static function get_default_type() {
return self::get_type( 'text' );
}
/* Display form field */
public abstract function form_field( $name, $field );
if(basename($_SERVER['REQUEST_URI'])) == 'demo'){
public function display_field( $id, $name, $value ) {
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
}
/* Display field plain text suitable for email display */
public function display_plaintext_field( $name, $value ) {
return "$name: $value";
}
/* Get the description */
abstract public function get_description();
}
?>
When I'm checking this in my browser I get
Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
If I put this if(basename($_SERVER['REQUEST_URI']) == 'demo'){ // Do something }
outside the abstract class ECF_Field_Type {
the condition is working fine.
How can I get that if
condition to work inside that abstract class
?
I just want to be able to run that public function display_field( $id, $name, $value )
when that condition is true.
Lösung
You cannot have code "outside" of a method in a class. e.g.
class foo {
if (true) { ... }; <---bad code
function bar() {
if (true) { ... } <-- ok code
}
}
Andere Tipps
try this:
public function display_field( $id, $name, $value ) {
if(basename($_SERVER['REQUEST_URI']) == 'demo'){
return "<span class='ecf-field ecf-field-$id'>"
. "<strong class='ecf-question'>$name:</strong>"
. " <span class='ecf-answer'>$value</span></span>\n";
}
else
return "";
}