【问题标题】:$this->constant or $this->var in class constructor类构造函数中的 $this->constant 或 $this->var
【发布时间】:2020-02-19 05:08:34
【问题描述】:

我想知道下面的代码在结构方面是否有问题,如果不是,任何人都可以向我解释为什么它确实有效

class ClassA extends ClassB
{
    public function __construct()
    {
        $this->FILE_DIRECTORY = 'book/auido';
    }

    public function index()
    {
        $file_directory = $this->FILE_DIRECTORY;
        return $file_directory
    }
}

以上返回

'book/auido'

我知道这样做的正确方法是 public static $variable = 'string'; 并使用 self::$variable; 在类中的任何方法中访问它。

但我觉得我上面使用的方法是错误的,因为我不完全理解发生了什么以及它为什么有效。

【问题讨论】:

  • 一切都取决于你打算如何使用这个类以及它的作用。也许静态变量有意义,也许没有。也许硬编码一个值是有意义的,也许它没有:)
  • @lagbox 这是否符合常数?不管是在构造函数中传递。
  • 找到了我的问题herehere的答案

标签: php laravel class constructor constants


【解决方案1】:

你在这里如何使用FILE_DIRECTORY 不是一个常量,它只是一个大写的变量。

这是你将它用作常量的方式,供参考:

class ClassA extends ClassB
{
    const FILE_DIRECTORY = 'book/auido';

    public function index()
    {
        $file_directory = self::FILE_DIRECTORY;
        return $file_directory
    }
}

通常人们使用常量来表示永远不会改变的东西,例如 ISO 国家代码。您域中的任何内容都可能发生变化,因此此时配置通常会更好。

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多