Examples of using Require_once in PHP files
Updated at:
Use require_once to split your Function Compute PHP handler into multiple files. The handler file includes the helper file at load time using __DIR__ for a path relative to the current file's directory. Variables defined at the top level of the included file must be accessed via $GLOBALS inside the handler function.
The following example uses two files: a.php defines a global variable and a class, and b.php is the handler file that includes a.php and uses its contents.
a.php (helper file — defines shared variables and classes)
<?php
$appcode = 123456;
class Foo {
public $name = 'FooClass';
function sayhi() {
print 'Foo say hello!';
}
}
$foo = new Foo;b.php (handler file — includes a.php and defines the function entry point)
<?php
require_once __DIR__ . '/a.php'; // Use __DIR__ to resolve the path relative to this file
function handler($event, $context) {
echo $GLOBALS['appcode'] . PHP_EOL; // Top-level variables from a.php must be accessed via $GLOBALS
$GLOBALS['foo']->sayhi(); // Same applies to object instances created at the top level
$foo2 = new Foo; // Classes from a.php are available directly after require_once
$foo2->sayhi();
return $GLOBALS['appcode'];
}Is this page helpful?