如果条件,PHP语法错误

时间:2014-01-30 15:15:51

标签: php url if-statement conditional

我想在我的代码中包含这个if条件:

if(basename($_SERVER['REQUEST_URI']) == 'demo'){ // Do something }

我想在这个条件成立时触发我的代码的一部分,所以我的整个代码看起来像这样:

<?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();
}
?>

当我在浏览器中查看此内容时,我得到了 Parse error: syntax error, unexpected T_IF, expecting T_FUNCTION in if(basename($_SERVER['REQUEST_URI']) == 'demo'){

如果我将此if(basename($_SERVER['REQUEST_URI']) == 'demo'){ // Do something }置于abstract class ECF_Field_Type {之外,则条件正常。

如何让if条件在abstract class内完成?

我希望能够在条件成立时运行public function display_field( $id, $name, $value )

2 个答案:

答案 0 :(得分:5)

您不能在类的“外部”使用代码。 e.g。

class foo {
   if (true) { ... };   <---bad code
   function bar() {
      if (true) { ... } <-- ok code
   }
}

答案 1 :(得分:1)

试试这个:

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 "";
}