【问题标题】:How to access constant defined in child class from parent class functions?如何从父类函数访问子类中定义的常量?
【发布时间】:2011-01-26 16:26:23
【问题描述】:

我从 php.net 看到了这个例子:

<?php
class MyClass {

     const MY_CONST = "yonder";

     public function __construct() {

          $c = get_class( $this );
          echo $c::MY_CONST;
     }
}

class ChildClass extends MyClass {

     const MY_CONST = "bar";
}

$x = new ChildClass(); // prints 'bar'
$y = new MyClass(); // prints 'yonder'
?>

但 $c::MY_CONST 仅在 5.3.0 或更高版本中被识别。我写的课可能分布很多。

基本上,我在 ChildClass 中定义了一个常量,而 MyClass(父类)中的一个函数需要使用该常量。有什么想法吗?

【问题讨论】:

    标签: php oop class


    【解决方案1】:

    我无法让它与 const 一起使用,因为它打印“yonderyonder”(这就是关于常量的事情,它们不会改变),但它可以与 var 一起使用:

    <?php
    class MyClass {
    
         var $MY_CONST = "yonder";
    
         public function __construct() {
    
         echo $this->MY_CONST;
         }
    }
    
    class ChildClass extends MyClass {
    
         var $MY_CONST = "bar";
    }
    
    $x = new ChildClass(); // prints 'bar'
    $y = new MyClass(); // prints 'yonder'
    
    ?>
    

    【讨论】:

    • 2015 - 我们不需要 var
    • 是的,这个回复是 5 年前写的,当时还是一件事!
    【解决方案2】:

    代替

    $c = get_class( $this );
    echo $c::MY_CONST;
    

    这样做

    $c = get_class( $this );
    echo constant($c . '::MY_CONST');
    

    【讨论】:

      【解决方案3】:

      如果您需要访问类或对象的常量、属性、方法,您可以使用reflection,它提供了有关对象结构的更多详细信息。
      示例:

      class MainClass
      {
          const name = 'Primary';
      
          public $foo = 'Foo Variable';
      }
      class ExtendedClass extends MainClass
      {
          const name = 'Extended';
      }
      
      /**
       * From Class Name
       */
      
      //get reflection of main class
      $mainReflection = new ReflectionClass('MainClass');
      
      if($mainReflection->hasConstant('name'))
          var_dump($mainReflection->getConstant('name'));//Primary
      
      //get reflection of extended class
      $extendedReflection = new ReflectionClass('ExtendedClass');
      
      if($extendedReflection->hasConstant('name'))
          var_dump($extendedReflection->getConstant('name'));//Extended
      
      /**
       * From Objects
       */
      $main = new MainClass();
      $extended = new ExtendedClass();
      
      //get reflection of main class
      $mainReflection = new ReflectionObject($main);
      
      if($mainReflection->hasConstant('name'))
          var_dump($mainReflection->getConstant('name'));//Primary
      
      //get reflection of extended class
      $extendedReflection = new ReflectionObject($extended);
      
      if($extendedReflection->hasConstant('name'))
          var_dump($extendedReflection->getConstant('name'));//Extended
      

      【讨论】:

        【解决方案4】:

        使用static::MY_CONST怎么样?

        【讨论】:

        • 我不明白为什么人们会在其他答案中深入研究 OOP。您的解决方案是唯一正确且更简单的解决方案
        • 使用static 关键字访问const 有问题。你能解释一下为什么会这样吗? PHP Docs 也让我感到困惑。谢谢。
        • @checksum: 不,那是错误的——self::MY_CONST 在两种情况下都打印“yonder”——在子级中定义的常量。问题是“如何从父类函数访问子类中定义的常量?”。
        • 我很高兴这能奏效,但我只能摸不着头脑......为什么会这样?嗯,不管我的东西现在如何工作。谢谢海报!
        • 关于实现的注意事项:self::MY_CONST 基于 Late static bindings,在 PHP 5.3.0 中发布(在 git Added support for Late Static Binding. (Dmitry, Etienne Kneuss) 中实现)。核心实现在get_called_class()。 PHP Parse error: syntax error, unexpected T_STATIC。
        【解决方案5】:

        从 php 5.3 开始:

        使用static::MY_CONST


        更多详情请关注static

        在这种情况下,the keyword static 是对实际调用的类的引用。

        这说明了static $varstatic::$varself::$var之间的区别:

        class Base {
            const VALUE = 'base';
        
            static function testSelf() {
                // Output is always 'base', because `self::` is always class Base
                return self::VALUE;
            }
        
            static function testStatic() {
                // Output is variable: `static::` is a reference to the called class.
                return static::VALUE;
            }
        }
        
        class Child extends Base {
            const VALUE = 'child';
        }
        
        echo Base::testStatic();  // output: base
        echo Base::testSelf();    // output: base
        
        echo Child::testStatic(); // output: child
        echo Child::testSelf();   // output: base
        

        还要注意,关键字static 有两个完全不同的含义:

        class StaticDemo {
            static function demo() {
                // Type 1: `static` defines a static variable.
                static $Var = 'bar';
        
                // Type 2: `static::` is a reference to the called class.
                return static::VALUE;
            }
        }
        

        【讨论】:

        • 很好的解释
        • 使用静态调用静态方法与实例化和调用对象方法时的行为是否相同?每个方法前面的“static”关键字是有关
        • @NaturalBornCamper Child::testStatic()$child::testStatic() 没有区别。尽管 $child-&gt;testStatic() 也可以工作,但对于静态方法,您应该坚持使用 :: - 使用 -&gt; 会引发通知,并且可能会让其他开发人员感到困惑
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-15
        相关资源
        最近更新 更多