Question
I am trying to run a simple PHP script. It uses a function from another file, but currently it is not being loaded.
What is the best-practice way to set up my environment so that the files are automatically linked? How do PHP developers address this with only use
, without using include
/require
(or equivalent)?
Goal, via PSR-12 - only use
:
The following example illustrates a complete list of all blocks:
<?php
/**
* This file contains an example of coding styles.
*/
declare(strict_types=1);
namespace Vendor\Package;
use Vendor\Package\{ClassA as A, ClassB, ClassC as C};
use Vendor\Package\SomeNamespace\ClassD as D;
use Vendor\Package\AnotherNamespace\ClassE as E;
use function Vendor\Package\{functionA, functionB, functionC};
use function Another\Vendor\functionD;
use const Vendor\Package\{CONSTANT_A, CONSTANT_B, CONSTANT_C};
use const Another\Vendor\CONSTANT_D;
/**
* FooBar is an example class.
*/
class FooBar
{
// ... additional PHP code ...
}
Example
And here is my attempt:
.
|- main.php
L- greet.php
main.php
<?php
declare(strict_types=1);
namespace Foo\Bar;
use function Foo\Bar\greet;
greet("joe");
?>
greet.php
<?php
declare(strict_types=1);
namespace Foo\Bar;
function greet(string $name): void {
print("hello $name");
}
?>
Command is,
php main.php
Output,
Fatal error: Uncaught Error: Call to undefined function Foo\Bar\greet() in /home/ders/projects/test/main.php:9
PHP info
$ php -v
PHP 8.2.3 (cli) (built: Mar 13 2023 03:01:45) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.3, Copyright (c) Zend Technologies
It doesn't exactly help that my setup for VSCode is pretty weak, being somewhat new to the language.