Reputation: 565
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?
Upvotes: 1
Views: 4258
Reputation: 5071
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();
?>
Upvotes: 0
Reputation: 2643
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!
Upvotes: 0
Reputation: 150
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();
Upvotes: 2
Reputation: 1248
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?
Upvotes: 0