简体   繁体   中英

In PHP, how do I call master class functions to different pages?

I have master class for the whole project. I need to call master class functions to different pages and methods as described below:

Master.php

class master{

    function login_parser(){

    }
}

Index.php

include('master.php')

function test(){
    $obj = new master();
}

function test2(){
    obj = new master();
}

I need to call object for every method. Is there any way to call an object in single time?

You could give that object as a parameter to the function, so it's also clear that there is a dependency to this object which can also be typehinted (which gets lost if just using it via global)

$obj = new master();

function test(master $obj) {
  ...
}

and then call:

test($obj);

There are a lot of ways to achieve this

Tobias Zander gave the option of parameters (dependency injection)

pros: know what the function needs

cons: could end up with giving a lot of parameters to a function

$obj = new master();

function test(master $obj) {
  ...
}

The second way could be using globals

pros: no paramter chain

cons: don't know what dependencies the function has

$obj = new master();

function test(){
    global $obj; //Now carry on
}

The third way, singleton

pros: object orientated way

cons: dont know the dependencies

In this your master class needs a static function that returns itself

class Master
    {
    protected static $master ;

    public static function load()
    {
        if(!self::$master instanceof Master) {
            self::$master = new Master();
        }

        return self::$master;
    }
}

Now i can use the master every where in my script using the load function, and it will only be initiated once

function test()
{
    $master = Master::load();
}

I personaly use method 1, but than for a class class Test { protected $master;

    public function __construct(Master $master) 
    {
        $this->master = $master;
    }

    public function whoo()
    {
        // now I can use $this->master as the master class
    }
}

Yes, Instead of creating object everytime. Create on outside the functions on global scope.

include('master.php')
$obj = new master();

function test(){
    global $obj; //Now carry on
}

function test2(){
    global $obj;
}

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