从类 2 调用类 1 的函数而不扩展?
如果我有两个类 A、B,其中一个不扩展另一个类,它们是独立的,但都加载到脚本中,我仍然可以从 B 引用 A 中的函数吗?
class A {
function one() {
echo "Class A";
}
}
class B {
function two() {
echo "Class B";
A::one();
}
}
$a new A;
$b = new B;
$b->two();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从表面上看,是的,你可以做到这一点。但是,类
A
中的函数one()
需要声明为static
才能使调用表示法正常工作。 (这使其成为类方法。)代码最后几行建议的另一种选择是让实例
$b
调用实例$a
。此类函数称为实例方法,是您通常与对象交互的方式。要访问这些方法,必须将它们声明为public
。声明为private
的方法只能由该类内的其他方法调用。有多种方法可以在代码中调用实例方法。这些是明显的两个,您可以将
$a
作为参数传递给函数,或者您可以在方法内创建类A
的实例。你到底想达到什么目的?
On the face of it, yes, you can do this. However, function
one()
in classA
needs to be declared asstatic
for your call notation to work. (This makes it a class method.)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 aspublic
. Methods declared asprivate
can only be called by other methods inside that class.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 classA
inside your method.What are you actually trying to achieve?
你可以这样定义它。
You can define it like this.
您可以将其定义为静态,但为什么要这样做呢?
You can define one as static, but why would you do such a thing?