从类 2 调用类 1 的函数而不扩展?

发布于 2024-11-30 12:35:01 字数 278 浏览 1 评论 0原文

如果我有两个类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

菩提树下叶撕阳。 2024-12-07 12:35:01

从表面上看,是的,你可以做到这一点。但是,类 A 中的函数 one() 需要声明为 static 才能使调用表示法正常工作。 (这使其成为类方法。)

代码最后几行建议的另一种选择是让实例 $b 调用实例 $a。此类函数称为实例方法,是您通常与对象交互的方式。要访问这些方法,必须将它们声明为 public。声明为 private 的方法只能由该类内的其他方法调用。

有多种方法可以在代码中调用实例方法。这些是明显的两个,您可以将 $a 作为参数传递给函数,或者您可以在方法内创建类 A 的实例。

你到底想达到什么目的?

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.)

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.

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?

眼睛会笑 2024-12-07 12:35:01

你可以这样定义它。

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

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


$a new A; 
$b = new B;

$b->two();

You can define it like this.

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

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


$a new A; 
$b = new B;

$b->two();
隔岸观火 2024-12-07 12:35:01

您可以将其定义为静态,但为什么要这样做呢?

You can define one as static, but why would you do such a thing?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文