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?

Tupic
  • 545
  • 1
  • 6
  • 12

4 Answers4

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();
Eduan Lenine
  • 150
  • 1
  • 11
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?

Community
  • 1
  • 1
Christopher Stevens
  • 1,214
  • 17
  • 32
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!

Max
  • 2,561
  • 1
  • 24
  • 29
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();
?>
Rehmat
  • 4,681
  • 3
  • 22
  • 38