views:

90

answers:

1

Hi there programmers!

I'm building a little MVC system (learning) and I have some problems with showing variables in my view files.

This is from my View class:

private $vars = array();

    public function __set($key, $value)
    {
        $this->vars[$key] = $value;
    }


    public function __get($key)
    {
        return $this->vars[$key];
    }

    public function __toString()
    {
        return $this->vars[$key];
    }

    public function show($file)
    {
        global $router;
        $folder = strtolower($router->current_controller);

        $path = VIEWPATH.$folder.'/'.$file.'.phtml';
        if ( ! file_exists($path))
        {
            die("Template: $file, not found");
        }
        include ($path);
    }

And here is from my controller:

$test = new View();
$test->name = 'karl';
$test->show('name_view'); 

And the view file (name_view)

echo $name // doesn't work
echo $this->name // Works

What am I doing wrong? Perhaps I haft to make something global?

THX / Tobias

EDIT: I just extracted the vars array in the view class right before I include the view file and then it worked.. Thank you for all help.

+6  A: 

There is no $key in __toString()!

Also __toString() doesn't accept any parameters!

Test it with this:

public function __toString()
{
    return json_encode($this->vars);
}


After your edit I realized that your problem is not on the __toString() method (you can just delete it since you're not using it). Doing echo $this->name is the correct way to show variables from inside your view in your case, however if you want to just do echo $name may I suggest a different approach?

function View($view)
{
    if (is_file($view) === true)
    {
     $arguments = array_slice(func_get_args(), 1);

     foreach ($arguments as $argument)
     {
      if (is_array($argument) === true)
      {
       extract($argument, EXTR_OVERWRITE);
      }
     }

     require($view);
    }
}

Use the View function like this:

$data = array
(
   'name' => 'karl',
);

View('/path/to/your/name_view.phtml', $data);

Now it should work just by doing echo $name;, you can adapt it to your View class if you want to. If that doesn't work, try changing the name_view view extension to .php.

Alix Axel
OK, I just get "Undefined variable:"
sandelius
It works, try placing the method inside the view class and doing `$test = new View();` and `echo $test;` You should get a dump of all the variables.
Alix Axel
if I echo $test in my controller then the json string shows up. But how do I get to us each vars in the view file then?
sandelius
and if I echo $test->name the value (karl) shows up. But I can't use them in my view files. Why is that?
sandelius
@sandelius, I provided a solution to accessing variables by their name
cballou
What about `echo $this->name;`? Does that work inside your view file?
Alix Axel
yeah "echo $this->name;" works fine
sandelius