简体   繁体   English

来自其他类的PHP调用来自子类的父方法

[英]PHP call from other class the parent methods from child

I've 3 classes in my project (connection , parent and child class). 我的项目中有3个班级(connection,parent和child班级)。

Parent

class Upload {

   public function UploadFile(){
        /* some code */     
   } 
}

Child 儿童

class Photos extends Upload {

  public function getUrl(){
      /* some code */           
  } 

  public function UploadPhoto(){

     $this->getUrl();   

     $this->UploadFile();       
  } 
}

Now, I'd like to create a class that can use the methods of other classes. 现在,我想创建一个可以使用其他类方法的类。

Class Example {

private $db;
private $ph;

     public function __construct( Mysqliconn $db, Photo $ph) {

        $this->db = $db;    
        $this->ph = $ph;   
     } 

     public function callUploadPhoto() {

        $this->ph->UploadPhoto();
     }
}

instantiated in this way 以这种方式实例化

$db = new Mysqliconn();
$ph = new Photos($db);
$ex = new Example($db, $ph);

My problem is that I can call the methods of other classes but not the method that refers to the parent class. 我的问题是我可以调用其他类的方法,但不能调用引用父类的方法。 If I call $ex->callUploadPhoto() that calls getUrl() method of photos class but not the parent Upload method Upload() . 如果我调用$ ex-> callUploadPhoto() ,它调用照片类的getUrl()方法,而不是父上载方法Upload() How could I do this? 我该怎么办? thanks 谢谢

try to use new php 5.4.0 future traits 尝试使用新的PHP 5.4.0未来 特性

that can solve your problem very easily... 可以很容易地解决您的问题...

What exactly is the error you are getting? 您得到的错误到底是什么?

and what is $name variable in UploadPhoto function line 2 ie, $this->Upload($name)? 在UploadPhoto函数第2行中的$ name变量是什么,即$ this-> Upload($ name)?

Your Example class needs to extend the Photos class. 您的Example类需要扩展Photos类。 That fixes it. 那就解决了。

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

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