Jump to content

Variables not working


newbtophp

Recommended Posts

Ok im including a file (global.php) at the top of my php file(s).

 

global.php:

<?php
function message($message){
echo $message;
}
$error[1] = "{$_SESSION['username']), this is not your post to edit.";
$error[2] = "Your PM has been sent to {$to}";
//contiguously...
?>

 

other.php:

<?php
include "global.php";
//code....
$date = time();									
$send = mysql_query("INSERT INTO `".$pm_table."` ( `pm_id` , `pm_to` , `pm_from` , `pm_date` , `pm_subject` , `pm_text` , `pm_status` )	VALUES ('', '$to', '".addslashes($_SESSION['username'])."', '$date', '$subject', '$message', 'new')"); 							
message($error[2]);	
?>

 

In other.php it echos:

 

Your PM has been sent to 

 

No {$to} ? (does'nt display the username). Even though $to is defined in other.php, I've even tried adding global $to; within the message() function.

 

Is their any way I can allow variables within the $error array, which are defined in other php file(s) where the message() function is called?

 

:-\

 

Link to comment
https://forums.phpfreaks.com/topic/197909-variables-not-working/
Share on other sites

Variable assignment takes on the value when the assignment statement is executed (fancy way of saying the value in the $error array elements are set when the code in global.php is executed.)

 

You can use a simple template and place-holders. In the following {x} is a place-holder in any message, x = 1, 2, 3, ...

<?php
$error[2] = "Your PM has been sent to {1}";
$error[3] = "Demo showing more than one place-holder - {1}, {2}, {3}, repeat the second one {2}";
function message(){
$arg_list = func_get_args(); // array of the passed arguments
$text = preg_replace('/\{(\w+)\}/e', "\$arg_list['$1']", $arg_list[0]);
echo $text; 
}
$to = 'some to name';
message($error[2],$to);
echo "<br />";
message($error[3],'first value','second value','third value');
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.