PrStandup
PrStandup

Reputation: 343

Calll a function from child class

Given I have an abstract class:

abstract class User{

  private function getNumber(){

      return 'Get number';
  }
}

With the child class

class UserComments extends User{


   public function rows(){
    return $this->getNumberOfRows();
 }
}

Question:

Is there any way to call the getNumber function when I try to call getNumberOfRows method in child class, or when I call getNumberOfRows() in child class I want getNumber to be called instead ?

Upvotes: 0

Views: 69

Answers (3)

AamirR
AamirR

Reputation: 12198

Abstract methods cannot be private, abstract must be implemented by the class that derived it.

You can either use public, or if you do not want it to be visible outside, make it protected, as following:

abstract class User{
    abstract protected function getNumber();
}

Once you do this, you can implement the getNumber method in User class:

class User {
    protected function getNumber() {
        // Do something
    }
}

Update: Please note that protected methods are accessible by child classes, you can use "hierarchy":

abstract class User{
    abstract protected function getNumber();
}

class UserComment extends User {

    protected function comment() {
        // Do something
    }

    protected function getNumber() {
        return 3;
    }

}

class Post extends UserComment {

    public function myMethod() {
        echo $this->getNumber();
    }

}

Also you can use interfaces, just an example:

interface User {
    public function getNumber();
}

class UserComment {
    protected function myMethod() {
        // Do something
    }
}

class Post extends UserComment implements User {

    final public function getNumber() {
        return 3;
    }

    public function myMethod() {
        echo $this->getNumber();
    }
}

$post = new Post();
$post->myMethod();

Upvotes: 1

Amit Merchant
Amit Merchant

Reputation: 1043

You can do something like this

abstract class User{

  private function getNumber(){

      return 'Get number';
  }

  public function getNumberOfRows(){

      return $this->getNumber();
  }
}

With the child class

class UserComments extends User{

   public function rows(){

      return $this->getNumberOfRows(); //Defined in the parent class
   }
}

Upvotes: 1

fab
fab

Reputation: 455

Due to PHP's Object inheritance you can directly call the specific method. However, in your example the getNumberOfRows() function is missing.

class UserComments extends User {

   public function rows() {
      return $this->getNumber();
   }
}

Upvotes: 1

Related Questions