0

I want to access to my function connectDB() in Db.php, from index.php but it keeps saying : "Undefined function 'connectDB'". Here's the codes.

Db.php

namespace App\kernel;

/**
 * Connect to a DB
 *
 * @return \mysqli
 */
function connectDB(): \mysqli
{
    $server="localhost";
    $user="root";
    $pass="";
    $db="xp";
    $connexion = mysqli_connect($server, $user, $pass, $db);
    if (!$connexion)
        die("La connexion à échoué : " . mysqli_connect_error());
    return $connexion;
}

index.php

use App\kernel\Db;

$db = connectDB();
if( !$db )
{
   exit();
}

echo 'success';

composer.json

{
    "name": "fl/xp",
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "require-dev": {
        "symfony/var-dumper": "^5.4"
    }
}

Thanks for your help.

Alpe Popas
  • 11
  • 2
  • You need to use the [`use function`](https://stackoverflow.com/a/20933938/231316) syntax, or fully qualify it. Unless you have a _class_ named `App\kernel\Db`, that `use` statement doesn't do anything. – Chris Haas Dec 30 '21 at 14:46
  • So if I have 10 functions I need to use "use function" 10 times ? – Alpe Popas Dec 30 '21 at 14:52
  • Yes, each named thing needs to be brought into scope, PHP doesn't have a concept of importing an entire namespace. Most people would solve this by wrapping their functions into a class and importing just that class. – Chris Haas Dec 30 '21 at 14:54
  • I have see this post : https://stackoverflow.com/questions/8104998/how-to-call-function-of-one-php-file-from-another-php-file-and-pass-parameters-t/31890917 But it don't answer my question, because I have the same thing, except I use namespace. Can 'namespace' break this ? – Alpe Popas Dec 30 '21 at 15:07
  • Yes, using a namespace changes this because PHP cannot resolve the symbols. If the code _calling_ the namespaced functions also lives in the same namespace, however, it will work. – Chris Haas Dec 30 '21 at 15:12
  • So if I remove the namespace, it will works ? – Alpe Popas Dec 30 '21 at 15:19
  • By removing the `namespace` portion, you put your code into the global/root/default namespace, so as long as the calling code does the same it should work. – Chris Haas Dec 30 '21 at 15:43
  • Thanks it solves my probleme, but I'm sad I can't use namespace – Alpe Popas Dec 30 '21 at 16:01
  • As pointed out above, namespaces are usually used together with classes to solve that problem. – Barmar Dec 30 '21 at 16:03
  • @AlpePopas, why can't you use namespaces, or conversely, why do you need/want to use them? If you code is isolated, no dependencies, you generally don't need a namespace, but if you are using third-party code, if it is semi-modern, there's a good chance that it is using namespaces. That said, function-only code (non-OOP) does have a little more boilerplate when using namespaces. – Chris Haas Dec 30 '21 at 16:28

0 Answers0