Page 1 of 1

a problem with eval(), can anyone help me? thx

Posted: Wed Jan 14, 2009 9:42 am
by workspace
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


I am a beginner to php, and i got a problem with eval() function.
I hope the result of output is "i am peter", but now i got "i am Array['name']", , can anyone help me ? thx!!!

//========================================
code:

Code: Select all

<?php
class user
{
    private $vars= array();
    
    public function init()
    {
        $this->vars["name"] = "peter";
    }
    
    public function show()
    {
        $sayme = "i am $this->vars['name']";
        eval("?>" . $sayme . "<?");
    }
}
 
$me = new user();
$me->init();
$me->show();
?>

~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: a problem with eval(), can anyone help me? thx

Posted: Wed Jan 14, 2009 9:53 am
by mintedjo

Code: Select all

"i am [b]{[/b]$this->vars['name'][b]}[/b]"
Is one way to do it.
Indexed arrays cant be written in the way you did - only the first part before the square brackets is considered variable so $this->vars (being of type array) simply produced the string "Array". "['name']" followed as a normal string because it wasnt considered part of the variable.
For the record I think some people think the curly braces make the code unreadable or harder to understand. I'm indifferent as to whether they are good or bad. It's useful if you ask me.

Re: a problem with eval(), can anyone help me? thx

Posted: Wed Jan 14, 2009 10:02 am
by pickle
There's hardly ever a good reason to use eval() and this isn't one of them. Using eval() raises lots of security concerns & certainly isn't needed to just output a string. Change show() to this:

Code: Select all

function show()
{
    echo 'I am '.$this->vars['name'];
}

Re: a problem with eval(), can anyone help me? thx

Posted: Thu Jan 15, 2009 4:18 am
by workspace
thx for your replaies, i am already resolved this problem by add "{" and "}" tags, especially thx mintedjo~~ :)