Q
Q
Quber2015-09-03 03:27:06
PHP
Quber, 2015-09-03 03:27:06

How to force classes to implement the same method from parent class?

Good afternoon!
Let's say there are three classes. One parent and two children.
Example

class Parent
{
    public function getName()
    {
        return "Родитель";
    }
}

class Child1 extends Parent
{
    public function getName()
    {
        return "Дочерний 1";
    }
}

class Child2 extends Parent
{
    public function getName()
    {
        return "Дочерний 2";
    }
}

It is necessary that each newly created child class implements one method, let's say getName(). Moreover, the main condition is that the child class must not implement any interface and the parent class must have the same getName () method as the child ones.
It should turn out like this:
echo $parent->getName();
echo $child1->getName();
echo $child2->getName();

// Родитель
// Дочерний 1
// Дочерний 2

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kravchenko, 2015-09-03
@mydearfriend

<?php

class p {
  
  public $name = 'p';
  
  function getname(){
    return $this->name;	
  }
}

class c1 extends p {
  public $name = 'c1';	
}
class c2 extends p {
  public $name = 'c2';	
}

$p = new p;
$c1 = new c1;
$c2 = new c2;
echo $p->getname();
echo $c1->getname();
echo $c2->getname();

//pc1c2

H
heartdevil, 2015-09-03
@heartdevil

Hello.
Can't you make the parent abstract too?
For example:

abstract class Parent
{
    abstract public function getName()
    {
        return "Родитель";
    }
}

class Child1 extends Parent
{
    public function getName()
    {
        return "Дочерний 1";
    }
}

class Child2 extends Parent
{
    public function getName()
    {
        return "Дочерний 2";
    }
}

R
Ruslan Madatov, 2015-09-03
@inginer

Can traits be used ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question