1

I have two files like below

SomeClass.php

class SomeClass {
  public function display() {
    $content = file_get_contents("helloworld.php");
    eval($content);
  }

  public function helloWorld() {
    echo "hello World!";
  }

}

helloworld.php

<?php
  $this->helloWorld() ;
?>
<p>It's html expression</p>

As you can see, I tried to execute helloworld.php in the display function. Of course, It occur an error because the html tag is placed in the display function.

Is there any good way to execute helloworld.php text in the display function preserving helloworld.php code?

1
  • 1
    Why not just require helloworld.php? Commented Apr 30, 2011 at 5:49

4 Answers 4

2

If you're trying to execute a specific file in the context of the current code, why not use include or require?

Remember, if eval is the answer, the question is wrong.

If you really want to use eval here,

eval('?>' . $content);

should work. Yes, you can close and reopen the PHP tag inside. This is how certain template engines work.

Sign up to request clarification or add additional context in comments.

Comments

1

You can capture it with output buffering.

ob_start();
include "helloworld.php";
$content = ob_get_contents();
ob_end_clean();

Comments

1

There is no way to do this, unless you want to do string concatination.

I tested this with a few minor changes to the helloworld.php file as such it works:

$this->helloWorld() ;
?><p>It's html expression</p>

This shows that the text is run raw as if it were hard included.

Now if you DONT or CANT change the open <?php tag, you can go one of two ways.

The easy way (String Concatenation):

public function display() {
    $content = file_get_contents("helloworld.php");
    eval('?>' . $content); //append a php close tag, so the file looks like "?><?php"
}

The harder way (String Replace):

public function display() {
    $content = file_get_contents("helloworld.php");

    //safely check the beginning of the file, if its an open php tag, remove it.
    if('<?php' == substr($content, 0, 5)) {
        $content = substr($content, 5);
    }
    eval($content);
}

Comments

0

you can use include or require for this purpose.

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.