Search code examples
phptostringmagic-methods

__toString problems


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.


Solution

  • 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.