1

是否可以在 PHP 中使用函数范围的常量?

如果不是,对于我们需要在函数(而不是方法)中使用常量的情况,首选的替代方案是什么?

编辑

我的特定用例:

我有一个与数据库一起使用的函数。我想将表名(可能还有其他不会改变的信息,例如字段名)存储在一个常量中(而只是在连接字符串中“硬编码”它)。其他函数不需要知道我的表名。

4

1 回答 1

0

如果在 PHP 的较新版本上,也许您可​​以使用名称空间获得您想要的东西。

看看这个页面: http: //php.net/manual/en/language.namespaces.nsconstants.php

<?php
namespace my\name; // see "Defining Namespaces" section

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // see "Global Space" section

$a = strlen('hi'); // see "Using namespaces: fallback to global
               // function/constant" section

$d = namespace\MYCONST; // see "namespace operator and __NAMESPACE__
                    // constant" section
$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // see "Namespaces and dynamic language features" section
于 2013-03-21T16:10:53.850 回答