Reputation: 8335
I want to declare constants inside of a namespace. I want them not to be visible outside of it of course.
Using define() won't work because it makes constants global regardless of the namespace it's executed in (if i understood well).
So can i do :
namespace paths;
const models = 'Models/';
const views = 'Views/';
const classes = 'Classes/';
And somewhere else :
require_once(paths\models.'user.php'); // works
require_once(models.'user.php'); // fails
Also if i do :
namespace ns;
namespace subNs;
Am i in ns\subNs or in subNs ?
PS: i know doing require_once('Models/user.php'); would be simpler, but that's just an example.
Upvotes: 4
Views: 4564
Reputation: 4384
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
Upvotes: 1
Reputation: 6771
You can't do what you want.
the only way you can use the constant "models" in the require function if it is defined as you stated you do not want to do.
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
Upvotes: 1
Reputation: 29482
Ad 1. Yes you can. can be checked by running your example script; (but you may have to use \paths\constant
or use paths;
first)
Ad 2. subNs Can be checked by echo __NAMESPACE__;
Upvotes: 4