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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
workspace
Forum Newbie
Posts: 2
Joined: Wed Jan 14, 2009 9:36 am

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

Post 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.
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

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

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

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

Post 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'];
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
workspace
Forum Newbie
Posts: 2
Joined: Wed Jan 14, 2009 9:36 am

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

Post by workspace »

thx for your replaies, i am already resolved this problem by add "{" and "}" tags, especially thx mintedjo~~ :)
Post Reply