Can PHP namespaces contain variables?
Asked Answered
I

8

75

Can PHP namespaces contain variables? If so, how can this be accomplished?

Imperception answered 13/3, 2011 at 3:59 Comment(2)
Have you tried? If you have tried, what was the outcome?Redress
@Redress Or he could ask, get a proper answer and help future readers with it... instead of everyone having to "try it out" themselves.Richy
A
59

No. You can set a variable after declaring a namespace, but variables will always exist in the global scope. They are never bound to namespaces. You can deduce that from the absence of any name resolution descriptions in

There would also be no allowed syntax to locate variables in a namespace.

print \namespace\$var;      // syntax error

print "${namespace\\var}";  // "unexpected T_NS_SEPARATOR"
Ambiguity answered 13/3, 2011 at 4:10 Comment(0)
V
28

Try this

<?php
namespace App\login; 

$p = 'login';
$test2 = '\App\\'.$p.'\\MyClass';

$test = new $test2;
Vrablik answered 12/3, 2012 at 20:3 Comment(5)
namespace must be first line of file. Isn't it?Uranie
This most certainly works, I use it like this: $class = '\\'.$vendor.'\\'.$application.'\\Router'; return new $class();Navigate
what is the rule of using single or double `\`s here ?Credenza
@IstiaqueAhmed i don't think there's a rule here \A just happens to not be an escape character. its probably better to always escape the `` in this case either wayRemove
An explanation of the results would be very appreciated.Pizor
L
18

No they cannot, as mario said.

To encapsulate variables use Classes. Polluting the global variable space should definitely be avoided.

  • Example

    class_dbworker.php:

    class DbWorker
    {
        //properties and method logic
    }
    
    class DbWorkerData
    {
        public static $hugerelationsmap = array(....);
        public static ....
    }
    

    mainapp.php:

    include_once 'class_dbworker.php';
    print_r( DbWorkerData::$hugerelationsmap );
    
  • Example using namespaces

    class_dbworker.php:

    namespace staticdata;
    class DbWorker
    {
        //properties and method logic
    }
    
    class DbWorkerData
    {
        public static $hugerelationsmap = array(....);
        public static ....
    }
    

    mainapp.php:

    include_once 'class_dbworker.php';
    
    use staticdata as data;
    
    print_r( \data\DbWorkerData::$hugerelationsmap );
    
Loewe answered 8/9, 2013 at 6:53 Comment(0)
M
3

You can bound a variable to the namespace by wrapping the variable inside a function.

<?php
 namespace furniture;
// instead of declaring a $version global variable, wrap it inside a function
function version(){
 return "1.3.4";
}
?>
Manno answered 11/1, 2022 at 8:34 Comment(0)
A
1

It is not possible because $MYVARNAME is still in the global scope. Try following code.

namespace.php

<?php
    namespace MYNAME;
    use MYNAME as M;
    const MYVAR   = 'MYVARNAME';

    ${M\MYVAR}    = date('Y');
    echo $MYVARNAME;  // PRINT YEAR
    $MYVARNAME    = 'X';
    echo $MYVARNAME;  // PRINT X
    echo ${M\MYVAR} ; // PRINT X

    include('file.php');
?>

file.php

<?php
    ${MYNAME\MYVAR}=date('Y');
    echo $MYVARNAME;        // PRINT YEAR
    $MYVARNAME = 'X';
    
    echo $MYVARNAME;        // PRINT X
    echo ${MYNAME\MYVAR};   // PRINT X
    
    include('file2.php');
?>

file2.php

<?php
    namespace MYNAME2;
    use MYNAME2 as N;
    const MYVAR   = 'MYVARNAME';

    ${N\MYVAR}    = 'Y';
    echo $MYVARNAME;  // PRINT Y
    echo ${MYNAME\MYVAR}; /* PRINT Fatal error: Uncaught Error:
    Undefined constant 'MYNAME2\MYNAME\MYVAR' */
?>
Aorangi answered 7/10, 2019 at 15:23 Comment(0)
P
0

It can be done - sort of.

This is probably extremely bad and should never be done, but it is possible by using variable variables, and the magic constant for namespace. So a string-variable to name the variable we want to use, like so:

<?php
namespace your\namespace;

$varname = __NAMESPACE__.'\your_variablename'; //__NAMESPACE__ is a magic constant
$namespaced_variable = $$varname; //Note the double dollar, a variable variable
?>
Pickering answered 9/12, 2015 at 14:0 Comment(1)
The question was Can PHP namespaces contain variables? not Can PHP variables contain namespaces?Loewe
A
0

Store Complete classPath in Variable and use after 'new'.

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string.

<?php
$a = "namespace\\className"; // 'which will print namespace/className'
$obj = new $a;
?>
Amphimixis answered 28/11, 2020 at 20:41 Comment(0)
M
0

Alternate ways that can make code more organized:

Instead of like \view\header\$links:

(1) Backslashes in array key for imaginary nesting, Example:

$myVar['view\header\links'] = 'value';

// OR use multidimentional arrays

$view['header']['links'] = 'value';

(1.1) Use Global Array, Example

// START - SETUP

define('I', 'mySite_19582730');

// END - SETUP


// Usage:

$GLOBALS[I]['view\header\links'] = 'value';

// OR

$GLOBALS[I]['view__header__links'] = 'value';

(1.1.1) Functions to get & set value in Global Array

function set($key, $val){
    if (is_string($key)) $GLOBALS['site_8619403725'][$key] = $val;
    elseif (is_array($key)){
        foreach($key as $ky => &$vl) {
            $GLOBALS['mySite_19582730'][$vl] = $val;
        }
    }
}

function get($key){
    return @ $GLOBALS['mySite_19582730'][$key];
}

// Usage

set('view\header\search','<div></div>');
set(['view\header\logo','view\header\homeLink'], '<a href=""></a>');
get('view\header\search');

(2) Use __ (double underscores) in variable name to make imaginary nesting, Example:

$view__header__links = 'value';
Martainn answered 24/11, 2022 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.