D
D
Dimas1232014-11-13 10:09:37
PHP
Dimas123, 2014-11-13 10:09:37

How to make class inheritance?

I have class A, I also need a class that does everything the same as class A, but takes data from another table "table2".
Probably, it is better to pass the table name in the constructor and then the second class is not needed, right?
But I would like to solve this by creating a descendant class in which to change only table1 to table2. How to do it?

<?
class A {
  public $c;		
public function __construct() { 
    $query = "SELECT * FROM `table1`;";	
    //здесь код по раскладке данных из таблицы базы в переменные		
}	
  function f1() {
  //код
  return $r1;	
  }
} 
?>

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2014-11-13
@Dimas123

It is done like this:

class B extends A
{
  public function __construct()
  {
    $query = "SELECT * FROM `table2`;";	
  }
}

But I think in your case it is not advisable to do this if the constructor performs identical functionality. Add a variable in the constructor where you will slip the table name and use it in the select.

G
GavriKos, 2014-11-13
@GavriKos

Well, you're right - inheritance is not necessary here at all. If you really want to - you do different constructors in both classes - each one will initit a variable with the table name in its own way.

D
DancingOnWater, 2014-11-13
@DancingOnWater

class Student { }
 class GraduateStudent extends Student { }

However, I advise you to discover ORM:
https://en.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D...

N
NickyX3, 2014-11-26
@NickyX3

Well, in general, you can and as the author wants. Something like this.

class A {
  private $table = 'table1';
  public function __construct() {
    // some init
  }
  public function run () {
    // select * from $this->table
  }
}

class B extends A {
  public function __construct() {
    parent::__construct();
    // some init
    $this->table = 'table2';
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question