【问题标题】:Include filein array which in class [duplicate]在类中的数组中包含文件[重复]
【发布时间】:2013-01-07 15:43:49
【问题描述】:

可能重复:
Can I include code into a PHP class?
Include file in array

我有这个 php 代码

   <?php
   class Config {

   public static $__routes = array(

   "Home"                    => "index.php",
   "Support"                 => "support.php",
   "Ads"                     => "ads.php",

   );

   }

   ?>

我有这样的 ex.php 文件

"Upgrade"                 => "upgrade.php",
"Faq"                     => "faq.php",
"Tos"                     => "tos.php",

我想将 ex.php 文件包含在“类”中的“公共静态 $__routes 数组”中

有点像

   <?php
   class Config {

   public static $__routes = array(

   "Home"                    => "index.php",
   "Support"                 => "support.php",
   "Ads"                     => "ads.php",

   include 'ex.php';

   );

   }

   ?>

请问我该怎么做?

【问题讨论】:

  • 不,课堂让一切变得不同
  • 错过了,你的问题的答案在这里Can I include code into a PHP class?
  • 你为什么要尝试这个?你的目标是什么?这看起来越来越像“设计错误”

标签: php arrays class include


【解决方案1】:

你不能,我已经在你的last question中解释了为什么

每个文件本身必须是有效的 PHP 代码,因为仅包含 发生在运行时(即到达这行代码时),而不是 在解析时(即文件加载时)

现在不同的是,替代解决方案不起作用,因为您不能使用表达式(即A + B)初始化类属性,只能使用文字(标量值和标量值数组)

由于属性是静态的,你甚至不能使用构造函数,你必须在类之外分配它:

class Config {

   public static $__routes = array(

       "Home"                    => "index.php",
       "Support"                 => "support.php",
       "Ads"                     => "ads.php",

   );

   // ...
}

Config::__routes += (include 'example.php');

【讨论】:

  • 它的工作..非常感谢您的帮助
【解决方案2】:

那是行不通的。声明类属性时不能执行任何类型的评估。为什么不直接加入项目?

如果您只是必须在另一个文件中配置一些路由,那么我建议将此属性设置为受保护或私有,并让调用者使用静态方法来获取此信息。在这个静态方法中,您可以将静态属性数组中定义的路由与包含文件中的数组(不仅仅是您显示的数组段)中定义的路由连接起来,然后返回这个合并后的数组。

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 2013-01-07
    • 2015-10-05
    • 2011-04-28
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    相关资源
    最近更新 更多