[英]How to call a non-static method from another class
This's my second question, even thought, i answered the previous one, on my own. 这是我的第二个问题,甚至以为我自己回答了上一个问题。 Anyway, I have a basic problem with OOP, on how to call a non-static method from another class. 无论如何,我对OOP有一个基本的问题,那就是如何从另一个类调用非静态方法。 example: We have a class named A in a file A.class.php 示例:我们在文件A.class.php中有一个名为A的类
class A {
public function doSomething(){
//doing something.
}
}
and a second class named B on another file B.class.php 在另一个文件B.class.php上命名为B的第二个类
require_once 'A.class.php';
class B {
//Call the method doSomething() from the class A.
}
I think now it's clearn. 我认为现在已经清除。 How to : Call the method doSomething() from the class A ? 如何:从类A调用方法doSomething()?
Class B will need an object of Class A to call the method on: B类将需要一个A类对象来调用以下方法:
class B {
public function doStuff() {
$a = new A();
$a->doSomething();
}
}
Alternatively, you can create the instance of A outside of B and pass it into B's constructor to create a global reference to it (or pass it to an individual method, your choice): 或者,您可以在B之外创建A的实例,并将其传递到B的构造函数中以创建对其的全局引用(或将其传递给您选择的单个方法):
class B {
private $a = null;
public function __construct($a) {
$this->a = $a;
}
public function doStuff() {
$this->a->doSomething();
}
}
$a = new A();
$b = new B($a);
How about injecting class A into B, making B dependant on A. This is the most primitive form of dependency injection: 如何将类A注入到B中,使B依赖于A。这是依赖项注入的最原始形式:
class A
{
public function doSomething()
{
//doing something.
}
}
class B
{
private $a;
public function __construct( A $a )
{
$this->a = $a;
}
//Call the method doSomething() from the class A.
public function SomeFunction()
{
$this->a->doSomething();
}
}
This is constructed like this: 构造如下:
$a = new A();
$b = new B( $a );
You need to instantiate a an object of class A. You can only do this inside a method of class B. 您需要实例化一个类A的对象。您只能在类B的方法中执行此操作。
class B{
public function doSomethingWithA(){
$a = new A();
return $a->doSomething();
}
}
class B {
public function __construct()
{
$a = new A;
$a->doSomething();
}
}
I know this is an old question but considering I found it today I figured I'd add something to @newfurniturey's answer. 我知道这是一个老问题,但是考虑到我今天发现了这个问题,所以我想在@newfurniturey的答案中添加一些内容。
If you wish to retain access to class B within class A this is what I did: 如果您希望保留A类中B类的访问权限,这就是我所做的:
class A
{
private $b = null
public function __construct()
{
$this->b = new B($this);
if (!is_object($this->b) {
$this->throwError('No B');
}
$this->doSomething();
}
public function doSomething() {
$this->b->doStuff();
}
private function throwError($msg = false) {
if (!$msg) { die('Error'); }
die($msg);
}
}
class B {
public function doStuff() {
// do stuff
}
}
This is constructed like this: 构造如下:
$a = new A();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.