MR.masoud MR.masoud - 4 years ago 107
PHP Question

pass data to included file not working(php)

on my sample mvc project i have a render function that include the view file
and sometimes in my controller i want to pass success or error massage to view forms(from controller)

render function:


public function render($view)
{
include 'view/'.$view.'.php';
}


controller:

public function sendguide()
{
if(isset($_POST['submit']))
{
$success='ur massage posted successfully ';
$this->render('sendguide');
}
else
$this->render('sendguide');
}


and this is the part of view that i print success message in:

<tr>
<td align="right"> &nbsp
<input name='submit' type='submit' value='ثبت دزخواست' ><?php echo $success; ?>

</tr>


it seems when i set
$success
and sent it to my view the view have to print
success message but it didnt work!


what's i'm missing?
tnx

Answer Source

Variables from the current script will be accessible in an included file (providing they are assigned before the include).

However in your example, the $success variable is not accessible in the your render() function and therefore not available to the script you include from the function.

The PHP documentation describes exactly your problem with variable scope;

http://php.net/manual/en/language.variables.scope.php

You can pass the $success variable as a parameter to your render() function;

  public function render($view, $success='')
{
    include 'view/'.$view.'.php';
}

I added $success='' as a parameter. The ='' means if no value is provided it will default to an empty string.

Pass $success to the function in the function call;

  public function sendguide()
{
    if(isset($_POST['submit']))
    {
        $success='ur massage posted successfully '; 
        $this->render('sendguide', $success);
    }
    else
    $this->render('sendguide');
}

As a side note: I would assign $success a Boolean value (true/false) to pass to the function to define success or failure. Then in your view file you can check success: if($success) echo... an appropriate message to the user, rather than passing the message (String) around in the $success variable from your script.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download