我有一个旨在供用户编辑的php脚本,并在开始时设置了一些选项,包括允许的图像文件扩展名。

稍后,我想在对象构造函数中使用它来设置文件是否为图像。

$extensions = ["jpg", "jpeg", "gif", "png"];

class directory_entry {

  function __construct($name) {

    $this->name = $name;

    $extension = pathinfo($name, PATHINFO_EXTENSION);
    $this->is_image = in_array(strtoupper($extension), $extensions); // throws an error

    $this->image = $this->is_image($name);

  }
}

这是行不通的,因为我不能从类(?)内部调用$extensions 有没有一种方法可以在此类的每个对象中不包含$extensions呢? 似乎坚果声明对象

$files[] = new directory_entry($value, $extensions);

并且该类的每个实例都具有相同数组的副本吗?

===============>>#1 票数:0

为什么不为此创建类?

class ExtensionsEnum
{
    const IMAGES = ["jpg", "jpeg", "gif", "png"];
}

然后

use ExtensionsEnum;

class directory_entry {
...
    $this->is_image = in_array(strtoupper($extension), ExtensionsEnum::IMAGES); // throws an error
...
}

===============>>#2 票数:0 已采纳

似乎最适合我想做的事情的解决方案(请记住,我是PHP和OOP n00b)是globals关键字:

$extensions = ["jpg", "jpeg", "gif", "png"];

class directory_entry {

  function __construct($name) {

    $this->name = $name;

    $extension = pathinfo($name, PATHINFO_EXTENSION);
    global $extensions; //use the global version of $extensions
    $this->is_image = in_array(strtoupper($extension), $extensions); // works!

    $this->image = $this->is_image($name);

  }
}

  ask by Alesh Houdek translate from so

未解决问题?本站智能推荐: