The confusion is when to instantiate a parent from a child class in php

I am building a website, but in order to improve my coding skills, I am trying to do this using the power of OOP.

I use classes to validate form input, so I thought that I would have a “parent” validation class, and then child classes for each form to be submitted (for example, an input class, registration class, etc.), which will take care of the right values ​​in the database etc.

The code I saw has a parent created from a child constructor. However, I did not do this, but it seems my class is working?

Can someone explain to me why we are calling the parent constructor from the child? Also, my code only works because I have “public” functions (methods) with my parent? (is this a potential problem)?

My code (shortened version for clarity) is below:

class Validation_Class
{
 public function __construct()
{
 // constructor not needed
 }

 public function is_genuine_email_address($email) {
     // code to validate email are genuine here...
     }

 }

My child class looks like ...

class Login_Class extends Validation_Class
{

public function __construct()
{
    // I don't call parent::__construct() from here
    // should I be doing?
    // I can still access parent methods with $this->is_genuine_email_address
    }

 }

All my functions (methods) in my Validation_Class are "publicly available", and when I instantiate my child class, I can call any of the methods of the validation class with:

$className = "Login_Class";
$thisClass = new $className();
+4
source share
3 answers

No need to call parent constructor

class Parent {
  //maybe just holding some constants
  public $database = 'mydatabase';
}

class Child extends Parent {
   public function myFunction() {
     if ($this->database == 'myDatabase') {
       // you can access the parents data without calling a constructor
     }
  }
}

. -, , __construct - ,

class Parent {
  public $database = null;
  public function __construct() {
    // example -> login to database
  }
}

class Child extends Parent {
  public function __construct() {
    parent::__construct();
    // .. further code
  }

  public function myFunction() {
     // do something, like executing a query
     $this->database->executeQuery($SQL);
  }
}

PHP "", , , - . ,

$object = new MyClass();
$object->instantiate()

__construct new ClassName() . , . , , , .

+4

. OO , , .

Login . Login .

, , "", "". , Login Validation, . .

, , . , , , .

, , , , , , .

+4

. ,

0

Source: https://habr.com/ru/post/1525509/


All Articles