代码之家  ›  专栏  ›  技术社区  ›  JD Isaacks

如何封装文件include?

  •  0
  • JD Isaacks  · 技术社区  · 15 年前

    如果我有一个类包含一个常数如下的文件:

    define("FOO", "bar");
    

    有没有一种方法可以让类包含带有封装的文件,所以如果我在某个已经有 FOO 它不会坏吗?

    3 回复  |  直到 15 年前
        1
  •  1
  •   RobertPitt    15 年前

    创建静态类并使用常量是封装特定常量的最佳方法:

    static class Constants
    {
        const Name = 'foo';
        const Path = 'Bar';
    }
    

    然后像这样使用:

    echo Constants::Name; //foo
    echo Constants::Path; //bar
    

    function _defined($key,$check_classes = false)
    {
        if($check_classes)
        {
            foreach(get_declared_classes() as $class)
            {
                if(constant($class . '::' . $key) !== null)
                {
                    return true;
                }
            }
        }
        if(!defined($key)) //global Scope
        {
            return true;
        }
    }
    

    用法:

    class a
    {
        const bar = 'foo';
    }
    
    if(_defined('bar',true)) //This would be true because its within a
    {
        //Blah
    }
    

    如果你这么想

    class a
    {
        const b = '?';
    }
    class b
    {
        const b = '?';
    }
    

    这些常量在类范围内,因此它们不会相互影响!

        2
  •  0
  •   Ivan Nevostruev    15 年前

    您可以检查是否已使用 defined :

    <?php
    define("FOO", "1");
    if (!defined("FOO")) { ## check if constant is not defined yet
        define("FOO", "2");
    }
    echo FOO;
    ?>
    
        3
  •  0
  •   Gordon Haim Evgi    15 年前

    你可以使用一个类contant

    class Foo
    {
        constant FOO = 'bar'
    }
    

    但是,在使用常量之前,必须包含类 Foo::FOO . 使用常规常量的另一种方法是使用供应商前缀作为它们的前缀,以减少冲突的可能性,例如。

    define('JOHN_FOO', 'bar')
    

    define('JohnIsaacks\FOO', 'bar');
    

    但不管怎么说,我想知道你为什么需要这个。如果要加载类,只需添加 autoloader .

    推荐文章