J
J
JackShcherbakov2018-01-28 23:10:05
PHP
JackShcherbakov, 2018-01-28 23:10:05

How to access a variable from another namespace?

Hello!
Trying to access a variable from another namespace - doesn't work.
What am I doing wrong and is it possible to do this at all?
Here is the code itself:

<?php 
namespace Code1{
  function sayHi(){
    print "Передаю привет из code1";
  }
  $a = 1;
}
namespace Code2{
  function sayHi(){
    print "Передаю привет из code2";
  }
  $a = 2;
}
namespace{
  print "файл general.php успешно подключен";
  Code2\sayHi();	
  print "<br>" . \Code2\a;
}

?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasiliy_M, 2018-01-29
@Vasiliy_M

While any valid PHP code can be within a namespace, only classes (including abstracts and traits), interfaces, functions, and constants depend on it.
php.net/manual/ru/language.namespaces.definition.php
_ variables can't be used that way.
namespace Code1{
    function sayHi(){
        print "Передаю привет из code1";
    }
    CONST A = 1;
}
namespace Code2{
    function sayHi(){
        print "Передаю привет из code2";
    }
    CONST A = 2;
}
namespace {
    print "файл general.php успешно подключен";
    Code2\sayHi();
    print "<br>" . Code2\A;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question