Forum Moderators: coopster

Message Too Old, No Replies

Function to parse pseudo-code

         

thijsnetwork

7:24 pm on Aug 11, 2004 (gmt 0)

10+ Year Member



Hello everybody,

On my website I want to have one array that contains all text-related stuff, like notifications, information, etc. Some of them have variables in it, like: "You have 4 new messages". I thought I mark variables with things like [new] so $new will be [new] so it will be easier to translate.

I started writing a parser to parse a specified value of the array. But the values of the variables are defined outside the function and doesn't appear to be seen within the function :S

This is what I have untill now:


<?php

/* this is just an example containing one var, but sometimes a string contains zero, and sometimes 10 */
$lang = array();
$lang['new'] = 'You have got [num] new messages';

$num = 4;

function parse ($var) {

$var = str_replace(array('[', ']'), array('$', ''), $var);
eval("\$var = \"$var\";");
return $var;

}

echo parse($lang['new']);

?>

But this code won't work properly, It outputs:

You have got new messages

coopster

9:06 pm on Aug 11, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You are correct, it is a variable scope [php.net] issue. You can use any global variable in a function. Either you have to declare it within the function with the
global
keyword or you can use the superglobals array,
$GLOBALS
.
$var = str_replace(array('[', ']'), array("{\$GLOBALS['", "']}"), $var);
To be safe, I used the braces syntax.
You have got {$GLOBALS['num']} new messages 
You have got 4 new messages

thijsnetwork

6:08 am on Aug 12, 2004 (gmt 0)

10+ Year Member



It works!
Thanks a lot.