1

How can i make a multifunctional variable from a class? I have tried this, but i get the error Fatal error: Call to a member function doSomethingElse()

I have a class for example

class users { public_funtion getUser(){} public_funtion doSomethingElse(){} } 

I want to be able to call 2 functions in one call

$users = new Users() $user = $users->getUser()->doSomethingElse(); 

What is this called? and how do i get this?

1
  • Return your object within the function (return $this). Commented Jan 11, 2016 at 18:41

4 Answers 4

2

It's simple, the first method must return the own instance, to do that you need to return $this in the first method, like that:

class Users { public function getUser(){ return $this; } public function doSomethingElse(){ } } 

than you can do that:

 $users = new Users() $user = $users->getUser()->doSomethingElse(); 
Sign up to request clarification or add additional context in comments.

Comments

0

I can't answer with 100% confidence, but give this a shot (you may need to return something in those functions, perhaps a constructor function as well as seen here?): how to call two method with single line in php?

Comments

0

Seperate Users and user

class users { public function getUser(){ bla(); return $user; } } class user{ public function doSomethingElse(){} } $users = new Users() $user = $users->getUser()->doSomethingElse(); 

if you make getUser static you can even strike the line where you create instance of class Users

I would not go for doing as much as I can in one line. Strife for readability!

Comments

0

Seems like you are looking for chaining. You need to return your objects to achieve the goal. Here is an example:

<?php class Users { public function getUser() { return $this; } public function doSomethingElse() { return $this; } } $users = new Users(); $user = $users->getUser()->doSomethingElse(); ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.