Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

php - Call function of class ONE from class TWO without extend?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...