简体   繁体   中英

Access to a function of a class from another class

as the title says, I have a situation like:

require_once("connect.php") //database connection file

class one {

    private $mysqli;

    function __construct ($dbi) {
        $this -> mysqli = $dbi;
    }

    function one {
        // ... function using things like $this -> mysqli -> prepare and so on...
    }
}

and, in the same file:

class two {
    private $mysqli;

    function __construct ($dbi) {
        $this -> mysqli = $dbi;
    }

    function two {
        // here I need to access the function "one" of the class "one"
        // If i do something like $one = new one ($mysqli) I get an error on the __construct
    }
}

I am really getting mad at this, but I believe that is not so difficult since I'm a beginner with OOP in PHP. Hope that soneone out there can help me.

Ignoring the mysqli issue shouldn't it be something like this

$one = new one ($this->mysqli);

$two = new two($this->mysqli);
$two->two($one->one); // call pass function from one into two

and you'd change your declaration of 2 to be something like

function two($functiontorun) {

Now I'm not OO pro either in php (don't see the point in a non-out of order non-compiled language) but I believe you can also resolve this by having class 2 as an EXTENDS of class 1. Alternatively if you make your class 1 public and function one public then as long as class 1 is instanced with the new one etc before hand then you should inside of your function two be able to just call $one->one(); but I'm not 100% on that one

Though I am not quite sure if I understand your question (because of all the MySQL stuff), access to a method (= a function within an object) can be given using the public keyword:

    public function functionName( $parameter ) {
        \\ function stuff
    }

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