【问题标题】:usage of __DIR__ in a class在类中使用 __DIR__
【发布时间】:2014-08-24 05:19:46
【问题描述】:

我正在编写一个非常简单的 PHP 应用程序,它返回文件的路径并稍作修改。

这是我的代码:

<?php
class abc {

 private $path = __DIR__ . DIRECTORY_SEPARATOR. 'moshe' . DIRECTORY_SEPARATOR;

 function doPath() {
 echo $this->path;
 }

}


$a = new abc();
$a->doPath();

我得到错误:

PHP Parse error:  syntax error, unexpected '.', expecting ',' or ';' in /mnt/storage/home/ufk/1.php on line 4

Parse error: syntax error, unexpected '.', expecting ',' or ';' in /mnt/storage/home/ufk/1.php on line 4

由于某种原因,我无法使用 '.' 添加连接 __DIR__到另一个字符串。我错过了什么?

使用 PHP 5.5.13。

【问题讨论】:

  • 您想要做的是一种称为紧耦合的不良做法。如果您以后必须更改路径怎么办?你会修改代码!
  • 那我应该怎么做呢?
  • 相反,您应该将路径作为参数传递,例如 public function __construct($path){ $this-&gt;path = $path; } 然后 new abs(__DIR__ . '/moshe/');
  • 感谢您告诉我

标签: php dir


【解决方案1】:

在引入constant scalar expressions in PHP 5.6 之前,您无法动态定义类属性。此示例现在适用于现代 PHP 版本。

    private $a = 5 + 4;  // evaluated, wont work before PHP 5.6
    private $a = 9;      // works, because static value

您的解决方案:

class abs
{
    private $path;

    public function __construct()
    {
        $this->path = __DIR__ . DIRECTORY_SEPARATOR . "moshe" . DIRECTORY_SEPARATOR;
    }
}

【讨论】:

【解决方案2】:

You can't calculate properties in their class definition

如果您需要将变量初始化为只能由表达式确定的默认值,您可以使用构造函数来完成。

public function __construct ()
{
    $this -> path = __DIR__ . DIRECTORY_SEPARATOR. 'moshe' . DIRECTORY_SEPARATOR;
}

但是,由于各种原因,上面的设计非常糟糕,我不会在这里讨论。最好将路径作为参数传递,因为这将为您提供更大的灵活性。例如,如果你想测试这个类,你可以让它在测试时写入不同的位置,而不影响实时数据。

public function __construct ($path)
{
    if (!is_dir ($path)) {
        // Throwing an exception here will abort object creation
        throw new InvalidArgumentException ("The given path '$path' is not a valid directory");
    }

    $this -> path = $path;
}

【讨论】:

  • 是的,这就是答案,这个答案应该被投票和接受。但是你迟到了,这是时间问题。
猜你喜欢
  • 1970-01-01
  • 2013-08-04
  • 2015-12-08
  • 1970-01-01
  • 2021-05-09
  • 2021-11-06
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多