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 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; 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. 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 Quote 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. 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 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
Archived
This topic is now archived and is closed to further replies.