简体   繁体   English

PHP:实例化一个类并使用另一个类的方法

[英]PHP : instantiate a Class and using methods of another Class

I have a class, named A. I have another class named B that extends A. I must instantiate A, and not B, but I need to use the methods in B too. 我有一个名为A的类。我还有一个名为B的类,该类扩展了A。我必须实例化A,而不是B,但是我也需要使用B中的方法。 How can I do this? 我怎样才能做到这一点?

Class A
{
    public function foo() { }
}

Class B extends A
{
    public function bar() { }
}

$a = new A();
$a->bar();

I know that this is not possible, but I need of a solution for this. 我知道这是不可能的,但是我需要一个解决方案。

PS: I wish the title of this question is correct. PS:我希望这个问题的标题是正确的。

$a = new A();
$a->bar();

Will give you fatal error. 会给您致命错误。 Because bar() is not a method of class A . 因为bar()不是A类的方法。 So you can't call this using A class's object. 因此,您不能使用A类的对象来调用它。

This will work fine: 这将正常工作:

Class A
{
   public function foo() { }
}

Class B extends A
{
   public static function bar() {  }
}

$a = new A();
B::bar();

I think, you just misunderstood the syntax of PHP ( Which can be rather confusing sometimes ) 我认为,您只是误解了PHP的语法( 有时可能会造成混乱

The extends keyword does not extend the parent class ( A ), but does create a new class B which is a child of A . extends关键字不会扩展父类( A ),但会创建一个新类B ,它是A的子A B inherits A 's methods, but A itself is not altered. B继承了A的方法,但A本身未更改。

Can the methods in B become static? B中的方法可以变成静态的吗?

Class A
{
    public function foo() { }
}

Class B extends A
{
    public static function bar2() { }
}

$a = new A();
$a->bar();
B::bar2();

obviously it would make sense to name it something different, as B::bar() is overriding the A::bar() implementation. 显然,将其命名为不同是有意义的,因为B :: bar()覆盖了A :: bar()实现。

I think you might have your structure slightly off. 我认为您的结构可能会略有偏离。 Try to abstract what you want as a reusable code snippet into its own routine. 尝试将您想要的内容作为可重用的代码段抽象到其自己的例程中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM