9

I develop a project with Yii.

I need to require a plain .php file (not component, not a class, just a regular sequence of PHP functions definitions). What is the correct way to do this under Yii framework? Should I use plain require_once()?

require_once(Yii::app()->basePath . '/extensions/my-php-file.php');

Right?

2 Answers 2

11

Yes, that's correct.

Example:

require_once Yii::app()->basePath . '/extensions/PearMail/Mail-1.2.0/Mail.php';
Sign up to request clarification or add additional context in comments.

3 Comments

Require is not a function, no need for (): This is right: require_once Yii::app()->basePath . '/extensions/PearMail/Mail-1.2.0/Mail.php';
@lin: I know it is a statement and not a function. Your version certainly looks more pleasing, but I don't think it matters which one you use (except for readability, maybe).
Yii::$app is the static var for the Yii2 Application class, 'yii\web\Application'. i tried this and it worked for me require_once Yii::$app->basePath . '/extensions/PearMail/Mail-1.2.0/Mail.php';
6

Method in your question is fine, but forces file location to be always in same folder.

Flexible Yii::import is intented for loading classes only, and only classes whose name is same as filename.

However if you want to use aliases to get path to file, you can still benefit from aliases by using getPathOfAlias, like that:

require_once Yii::getPathOfAlias('application.extensions.my-php-file') . '.php';

To include file relative to current file it is good to use dirname(__FILE__) or __DIR__ (php 5.3+)

require_once __DIR__ . '/some-file.php';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.