PHP如何在函数外部的类体中“包含”代码 [英] PHP how to 'include' code in the body of a class, outside of a function
问题描述
我有一个Symfony2 Controller,我想在其中包含一个包含常用功能的文件。但是,当我使用require语句时,我收到一条错误消息,指出require是意外的。此外,在PHPStorm中,我还得到一个错误,说只有函数可以在我的require语句中声明。
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.
以下是我的代码概述:
<?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.
我宁愿不创建另一个包并使用它,因为我希望在调用utility.php中的函数时MyController类的范围生效。
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?
奇怪的是,当我查找包括并要求php手册和w3schools php页面似乎说你可以使用include / require来完成我在这里尝试做的事情。
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.
推荐答案
您可能正在寻找的是特质:
What you might be looking for are traits:
http:// php.net/manual/en/language.oop5.traits.php
使用traits可以加载您班级的其他功能。
Using traits allows you to load additional functionality to your class.
<?php
namespace AppBundle\Traits;
trait UtilityTrait {
public function doStuff() {
return 'stuff';
}
}
?>
<?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;
use AppBundle\Traits\UtilityTrait;
class MyController extends Controller {
use UtilityTrait;
....
}
这篇关于PHP如何在函数外部的类体中“包含”代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!