DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore

Class calling member function through Eval()

StackOverflow https://stackoverflow.com/questions/13216725
  •   php  -  eval
  •  | 
  •  
  •  | 
  •   ( words)

Question

Yes, I am quite aware of how horrible Eval() is, I have no choice, it is for an assignment and the professor has instructed us to use it.

I am having trouble figuring out why PHP won't let me call a class's member function from within the class when using Eval(). For example:

$code="class evalTest{
    function f1(){
        echo 'f1';
        f2();
    }
    function f2(){
        echo 'f2';
    }
}

$x=new evalTest();
$x->f2();
$x->f1();";

eval($code);
echo 'test';

The above code will print out:

f2f1

and the rest of the page will be blank. It seems like the entire PHP script stops as soon as I call a function from within a function through Eval(). Even the final "echo 'test';" is not printed.

Is there some trick to getting this to work, or is this a limitation of Eval()? Again, I would avoid using Eval() if I could, but we were specifically instructed to use it.

No correct solution

OTHER TIPS

Because you need to call $this->f2(); instead of f2().

You also need to escape $ if you are using double quotes, because any $blah in double-quote strings are interpreted as variable references.

<?php
$code="class evalTest{
    function f1(){
        echo 'f1';
        \$this->f2();
    }
    function f2(){
        echo 'f2';
    }
}

\$x=new evalTest();
\$x->f2();
\$x->f1();";


eval($code);
echo 'test';

Demo

use single quotes or protect \$, also you had error where you called f2(), use $this->f2 http://codepad.org/DkQ3PiTQ

$code='class evalTest{
    function f1(){
        echo "f1";
        $this->f2();
    }
    function f2(){
        echo "f2";
    }
}

$x=new evalTest();
$x->f2();
$x->f1();;';

eval($code);
echo 'test';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow