1

I have two files, the first one being in the main directory, console_output.php:

<?php
class console_output
{
  function write_to_logfile($text) {
    file_put_contents("log.txt", $text);
  }
}
?>

and the second one in a subdirectory, xController.php

<?php 
...import stuff...
include ("../console_output.php");

class xController extends Controller{
  ...do_stuff..

  function doMoreStuff(){
  ...

    $console_output = new console_output();
    $console_output->write_to_logfile("did Stuff");
  }
}
?>

This is all in Yii2 framework, in case that matters. I have tried with apps/console_output.php and ../console_output.php, but it fails either way. When I use apps/console_output.php, the error is

include(app/console_output.php) [https://secure.php.net/manual/en/function.include.php'>function.include.php]: failed to open stream: No such file or directory

The error is shown right at the include statement.

Using ../console_output.php in the include statement gives me an error at

$console_output->write_to_logfile("did Stuff");

with the message

Class 'app\controllers\console_output' not found

I have no idea what I'm doing wrong here. Can you help me out please?

1
  • You can use alias on yii2 to set the path for your files. docs list Commented Feb 17, 2020 at 8:01

2 Answers 2

1

Yii(2) offers multiple shortcuts to various paths. The most commonly used one is

Yii::$app->urlManager->baseUrl

So You can include your php file like:

$url = Yii::$app->urlManager->baseUrl.'/../console_output.php';
include $url;
Sign up to request clarification or add additional context in comments.

Comments

0

You relative path Def nation is wrong. You are using .. that mean you moving a director up from current script. You need to use "subdirectory/script.php"

3 Comments

but the include statement is in the file in the subdirectory, so if I want to call the function from the file in the main directory I have to move out of the subdir.
Where is log.txt located? Is it in same directory as console_output.php
yes. console_output and log.txt are together, xController in the subdirectory.

Your Answer

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