Question

I have a helper file that basically looks like this:

helper.php:
<?php
  function renderPartial($name) {
    return file_get_contents(__DIR__.'/'.$name.'.php');
  }

And I'm trying to call that function from within a view:

view.php:
<h2>Title</h2>
<?= renderPartial('_form') ?>

_form.php is in the same directory as view.php, so I want to search in that directory. The __DIR__ magical constant returns the directory of helper.php instead of view.php. Any way to include a helper file like that and return the directory of the file making the call instead of the file where the function is defined? I've searched through the PHP documentation, and I can't find any constants or helper functions.

Was it helpful?

Solution

You could pass the current __DIR__ as an argument

function renderPartial($name, $dir) {
    return file_get_contents($dir.'/'.$name.'.php');
}

and

<?= renderPartial('_form', __DIR__) ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top