Jump to content

accessing member variable in class


Recommended Posts

Hi,

Please consider the following code:

<?php
class a
{
     public function f()
     {
          $name = 'John';
     }
}

$name = new a()

echo $name->f()->$name;

 

By doing this, I thought I could echo the name John, but it displays nothing. Where did I make a mistake?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/
Share on other sites

Firstly, you would need to make $name a public property. Secondly, your f() method would need to return an instance of itself in order to be chainable.

 

<?php
class a
{
    public $name;

    public function f()
    {
        $this->name = 'John';
        return $this;
    }
}

$name = new a;
echo $name->f()->name;

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.