4

我想在命名空间内声明常量。我当然希望它们在它之外不可见。

使用 define() 将不起作用,因为它使常量全局化,而不管它在哪个名称空间中执行(如果我理解得很好)。

我可以这样做:

namespace paths;

const models  = 'Models/';
const views   = 'Views/';
const classes = 'Classes/';

在其他地方:

require_once(paths\models.'user.php'); // works
require_once(models.'user.php');       // fails

另外,如果我这样做:

namespace ns;
namespace subNs;

我在 ns\subNs 还是在 subNs 中?

PS:我知道做 require_once('Models/user.php'); 会更简单,但这只是一个例子。

4

3 回答 3

4

广告 1. 是的,你可以。可以通过运行示例脚本来检查;(但您可能必须先使用\paths\constantor use paths;

Ad 2. subNs 可以通过以下方式检查echo __NAMESPACE__;

于 2012-11-28T00:12:17.787 回答
1

你不能做你想做的事。

如果按照您声明的方式定义了您不想执行的操作,那么您可以在 require 函数中使用常量“模型”的唯一方法。

Why don't you write a class to do this?

<?php
class PATHS {

    public $models = null;
    public $views = null;
    public $classes = null;

    public function __construct($namespace) {

         switch ($namespace) {
            case 'path1' :
                $this->models = 'my_custom_path/models';
                $this->$views = 'my_custom_path/views';
                $this->classes = 'my_custom_path/classes';
             break;
             case 'path2' :
                $this->models = 'my_custom_path/models';
                $this->$views = 'my_custom_path/views';
                $this->classes = 'my_custom_path/classes';
             break;
             default :
                $this->models = 'my_custom_path/models';
                $this->$views = 'my_custom_path/views';
                $this->classes = 'my_custom_path/classes';
             break;
         }

    }

}

$paths =new PATHS('my_namespace');

echo $paths->models;
echo $paths->views;
echo $paths->classes;

?>

I don't fully understand what your end-goal is, but I think I get the gist of it, and a similar class turned into an object should accomplish what you want.

You can simply include that class in your framework where necessary.

Hope that helps

于 2012-11-28T00:14:44.953 回答
1

You CAN use define to declare namespace constants, like so:

<?php namespace paths;
// Preferred way in a file that does not declare the namespace:
define('paths\\models', 'Models/');
define('paths\\views', 'Views/');
define('paths\\classes', 'Classes/');

// Preferred way in file with the namespace declared:
const models  = 'Models/';
const views   = 'Views/';
const classes = 'Classes/';
?>

Coming in PHP 5.6, you will be able to auto load constants via the "use" keyword, see here: http://php.net/manual/en/migration56.new-features.php

于 2014-08-09T14:21:13.963 回答