dongtan3395 2013-03-14 10:48
浏览 32
已采纳

将静态变量用于全局配置参数的缺点

I know there are other ways to archive this, but the question is... which are the cons about something like:

MyGlobalConfig.php

<?php

namespace Acme\DemoBundle;

class MyGlobalConfig
{
    public static $uploadsDir;
}

AppKernel.php

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Acme\DemoBundle\MyGlobalConfig;

class AppKernel extends Kernel
{
    public function __construct($environment, $debug)
    {

        MyGlobalConfig::$uploadsDir = __DIR__ .'/../uploads';

        parent::__construct($environment, $debug);
    }

Article.php

<?php

namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Acme\DemoBundle\MyGlobalConfig;

/**
 * @ORM\Entity
 */
class Article
{
    protected function getUploadsDir()
    {
        return MyGlobalConfig::$uploadsDir;
    }
  • 写回答

1条回答 默认 最新

  • dougu2036 2013-03-14 11:08
    关注
    1. untestable code, since to test any of the using classes you need to be providing them with a MyGlobalConfig with values, but soon you'll notice that it would be really useful if ClassA received different config values than ClassB, so you start creating work-arounds for those. Or classA pollutes the global state with testing values, while ClassB needs original values. Etc. You keep on running around in circles.

    2. Unreusable code, all your config consumers depend on the same, probably monolithic, class. You can't take out a config consumer w/o taking the monolithic class with it.

    3. global state, i.e. modifiable from anywhere w/o a trace and therefore utterly unpredictable and fragile.

    4. less legible code

    Probably I forgot a few... It's basically global vars in disguise. Only constants are ok in a global scope, since they're immutable, but even so, many developers use way too many constants for stuff they shouldn't use them for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退