从类TWO调用类ONE的函数没有扩展? [英] Call function of class ONE from class TWO without extend?

查看:96
本文介绍了从类TWO调用类ONE的函数没有扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个类A,B和一个不扩展另一个,它们是分开的,但都加载到脚本中,我仍然可以从B引用函数A?

If i have two classes A, B and one does not extend another they are separate but both loaded into script can i still reference function in A from B?

class A {
    function one() {
        echo "Class A";
    }
}

class B {
    function two() {
        echo "Class B";
        A::one();
    }
}


$a new A; 
$b = new B;

$b->two();


推荐答案

这个。但是, A 类中的函数 one()需要声明为 static 为您的呼号记号工作。 (这使它成为一个类方法。)

On the face of it, yes, you can do this. However, function one() in class A needs to be declared as static for your call notation to work. (This makes it a class method.)

另一个替代方法,由代码中的最后一行建议, c $ c> $ b 调用实例 $ a 中的函数。这样的函数称为实例方法,是你如何正常地与对象交互。要访问这些方法,必须将它们声明为 public 。声明为 private 的方法只能由该类中的其他方法调用。

The other alternative, suggested by the last lines in your code, is for the instance $b to call a function in instance $a. Such functions are called instance methods and are how you normally interact with an object. To access these methods, they must be declared as public. Methods declared as private can only be called by other methods inside that class.

有几种方法可以调用实例方法。这些是你可以传递 $ a 作为函数的参数的明显的两个,或者你可以创建一个类 A

There are several ways to call an instance method in your code. These are the obvious two you can pass in $a as a parameter to the function, or you can create an instance of class A inside your method.

您实际上想要达成什么?

What are you actually trying to achieve?

这篇关于从类TWO调用类ONE的函数没有扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆