I have a Symfony2 Controller in which I want to include a file containing common functions. However, when I use the require statement I get an error saying that the require was unexpected. Also, in PHPStorm, I also get a error saying that only functions can be declared where I have my require statement.
Here is an overview of my code:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Response;
use ReCaptcha\ReCaptcha;
class MyController extends Controller {
private $salt_length = 10;
private $resources;
private $request;
private $session;
private $message;
private $loggedin;
/**
* @Route("/My/home")
*/
//
// My home page
//
public function homeAction() {
// bla bla
}
require 'utilities.php'; // <<==============
}
?>
The require at the end of my class produces the compiler error.
I'd rather not create another bundle and 'use' it because I want the scope of MyController class to be in effect when the functions in the utility.php are called.
Is there another preprocessor directive that does include the content of a file in another to achieve what I'm trying to do?
Oddly, when I look up include and require the php manual and w3schools php pages seem to say that you can use include/require to do exactly what I'm trying to do here.
Thank you in advance for any help someone can give me on this.
You can put whatever code you want outside the class definition and it will run when the class is loaded. I prefer creating a class of static helper functions instead of just global functions if you want to include non-class related helper type functions that have no state.
To note:
utilities.php
is an actual class or classes, do the right thing and registier an autoloader instead.require_once
instead ofrequire
It's messy and I don't recommended it, but:
What you might be looking for are traits:
http://php.net/manual/en/language.oop5.traits.php
Using traits allows you to load additional functionality to your class.