programming.name Posted May 18, 2010 Share Posted May 18, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/ Share on other sites More sharing options...
trq Posted May 18, 2010 Share Posted May 18, 2010 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; Quote Link to comment https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/#findComment-1059879 Share on other sites More sharing options...
Mchl Posted May 18, 2010 Share Posted May 18, 2010 Maybe it's just me, but using chaining in this way smells. Quote Link to comment https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/#findComment-1059920 Share on other sites More sharing options...
ignace Posted May 18, 2010 Share Posted May 18, 2010 Maybe it's just me, but using chaining in this way smells. It sure does, besides I believe the OP actually isn't aware of __set($key, $value), __get($key), __isset($key), and __unset($key) or ArrayAccess. Quote Link to comment https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/#findComment-1059936 Share on other sites More sharing options...
Mchl Posted May 18, 2010 Share Posted May 18, 2010 Seems like he's just starting. Give him time Quote Link to comment https://forums.phpfreaks.com/topic/202119-accessing-member-variable-in-class/#findComment-1059942 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.