There is a file with data for connecting to the database, it is in a separate file. How to transfer data from it to another file?

    2 answers 2

    You can use the design namespace 's (php 7+)

    Example :

    The first option :

    Let there be a file ex1.php :

    <?php namespace example; class Ex{ public static $variable = 'Jack Sparrow'; } 

    And the file ex2.php , in which you need to use a variable from the class Ex $ variable :

     <?php include 'ex1.php'; //или любой другой оператор подключения файлов php (include_once, require, require_once) use example as ex; echo ex\Ex::$variable; //выведет Jack Sparrow /* или use example\Ex; echo Ex::$variable; */ 

    Yes, you need to connect the file anyway ( include operator).

    This approach is more preferable from the point of view of the PLO and more convenient in the case of large projects.

    In projects with an MVC structure, for example, here , you will not need to include such files in models (they are automatically connected in the Route class. And yes, that article was written in 2012, without using namespaces , but if you wish, you can easily add, it will be especially convenient if your project grows).

    The second option :

    Let there be a file ex1.php :

     <?php $variable = 'Test'; function doSomething($z){ echo $z; } 

    And the ex2.php file:

     <?php require 'ex1.php'; echo $variable; //Получим Test doSomething('Привет, русскоязычный Stackoverflow!'); //выведет надпись в кавычках 

    Variable and method from the file ex1.php , but by connecting it, we get access to them.

    It is important to note that you need to attach files before using them in a third-party file.

    This second example is suitable for small projects, or some small script.

    • And if I need to transfer data from another file to a class? - N. Turshiev
    • call_user_func_array php.net/call_user_func_array - azhirov1991
    • one
      In general, I advise you to use php.net/Autoload - azhirov1991 for work with classes

    Connect file via

     include 'file.php'; // или require 'file.php'; 

    And after connecting, you can use.

    • It is naturally desirable to do this at the very beginning :). - Alexey Shatrov
    • Not a fact, there are moments when you do not need to load an extra code. - user190134