miiikkeyyyy Posted February 11, 2011 Share Posted February 11, 2011 Here is my code: <?php class Test { function hello() { echo"hello"; } public function &world() { echo" world"; } } $test = new Test(); $test->hello() ->world(); ?> I know it can be done like: $test = new Test(); $test->hello(); $test->world(); ?> However I want it too look like: (as I believe it's cleaner) $test = new Test(); $test->hello() ->world(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/227348-php-class-hello-world/ Share on other sites More sharing options...
KevinM1 Posted February 11, 2011 Share Posted February 11, 2011 So, what's the problem? And why are you using the reference operator with your second method? Quote Link to comment https://forums.phpfreaks.com/topic/227348-php-class-hello-world/#findComment-1172675 Share on other sites More sharing options...
Jessica Posted February 11, 2011 Share Posted February 11, 2011 The only way that would work is if hello() returns an object that has the method world(); Just because you like the way it looks doesn't mean it's better :-P The first example is correct. $test->hello(); $test->world(); Quote Link to comment https://forums.phpfreaks.com/topic/227348-php-class-hello-world/#findComment-1172874 Share on other sites More sharing options...
lastkarrde Posted February 11, 2011 Share Posted February 11, 2011 First of all, remove the reference character (&) from public function &world() . PHP5 doesn't need references. To allow method chaining, just return $this from every method you want to be chainable. function hello() { echo"hello"; return $this; } Quote Link to comment https://forums.phpfreaks.com/topic/227348-php-class-hello-world/#findComment-1172993 Share on other sites More sharing options...
ignace Posted February 12, 2011 Share Posted February 12, 2011 add return $this; to hello() and world() remove the reference-operator (&) as objects are passed by reference by default. PHP5 doesn't need references Sure it does, especially when passing big array's. Quote Link to comment https://forums.phpfreaks.com/topic/227348-php-class-hello-world/#findComment-1173402 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.