How to create a function with the same context as require in PHP?
This question is due to an error when I try to use this on a file. I have a file with a class for the page:
class Page {
function whatHappen()
{
echo "this may work";
}
function helloWorld()
{
echo "This is my page!";
require( "usethis.php" ); // --> this works
similar_require( "usethis.php" ); // ---> with this I get an error
}
function write()
{
$this->helloWorld();
}
}
And a function that similar to require:
function similar_require( $filepath )
{
require( $filepath );
}
In usethis.php file I have this:
<?php开发者_C百科
$this->whatHappen();
?>
How to do work similar_require and require like the same function?
In usethis.php you are trying to access $this
, which is not declared in scope of similar_require
function.
Read about visibility: http://www.php.net/manual/en/language.variables.scope.php
All this code looks very dirty: don't use 'require' or 'include' in methods or functions - it's like using globals (and globals are very bad thing).
Maybe this will work:
function similar_require( $filepath, $this )
{
require( $filepath );
}
and
similar_require( "usethis.php", $this );
精彩评论