简体   繁体   中英

PHP create class object

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?

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();

我无法百分百地回答,但可以试一试(您可能需要在那些函数中返回某些内容,也许是构造函数以及在此处看到的内容?): 如何在php中用单行调用两个方法?

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!

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();
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM