简体   繁体   English

从另一个类访问类的功能

[英]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. 我真的很生气,但我相信这并不困难,因为我是PHP的初学者。 Hope that soneone out there can help me. 希望那里的人可以帮助我。

Ignoring the mysqli issue shouldn't it be something like this 忽略mysqli问题不应该是这样的

$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 并且你将2的声明改为类似的

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(); 现在我不是在PHP中的OO专业版(没有看到非乱序非编译语言中的点)但我相信你也可以通过将class 2作为class 1的EXTENDS来解决这个问题。或者如果你把你的1级公开并且一个公共的功能然后只要第1级用new one等实例化,然后你应该在你的函数内部两个能够只调用$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: 虽然我不太确定我是否理解你的问题(因为所有MySQL的东西),但是可以使用public关键字来访问方法(=对象中的函数):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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