Saint Robson
Saint Robson

Reputation: 5525

PHP Function from Inherited Class Requires Function from Another Class

I have this situation :

class User extends Database {

    public function validateLogin ($email, $password) {
       // some code here
    }

}

class General {
    public function encryptData ($data) {
       // some code here
    }
}

$password from validateLogin needs to be encrypted using encryptData function from class General, the problem is class User already extends / inherit class Database and PHP doesn't support multiple inheritance, right? how to solve this situation?

thank you

Upvotes: 1

Views: 34

Answers (4)

br3nt
br3nt

Reputation: 9576

You can use traits if you are using PHP 5.4+.

Example:

trait encryptDataFunctions {
  public function encryptData($data) {
    // some code here
  }
}

Then use it in your classes:

class General {
  use encryptDataFunctions;
}

class User extends Database {
  use encryptDataFunctions;

  public function validateLogin ($email, $password) {
    $encrypted = $this->encryptData($password);
    //more code here
  }
}

Upvotes: 1

STLMikey
STLMikey

Reputation: 1210

You could try making it a static method, and calling it directly without instantiating the General object:

class General {
    public static function encryptData ($data) {
       // some code here
    }
}

class User extends Database {
    public function validateLogin ($email, $password) {
       $encrypted = \General::encryptData($password);
       //more code here
    }    

}

Upvotes: 1

br3nt
br3nt

Reputation: 9576

Use some sort of base method on the base class like so:

class Database {
  protected function encryptData($data) {
    // this is just to give an idea... you could cache the
    // General class, rather than create it on each method call
    // sky's the limit
    $x = new General();
    return $x->encryptData($data);
  }
}

Then you can use that factory method in the subclasses:

class User extends Database {
  public function validateLogin ($email, $password) {
    $encrypted = $this->encryptData($password);
  }
}

You can even override it if need be:

class UnsecuredUser extends Database {

  protected function encryptData($data) {
    return $data;
  }

  public function validateLogin ($email, $password) {
    $encrypted = $this->encryptData($password);
  }
}

Upvotes: 1

PrinceG
PrinceG

Reputation: 982

You can inject class General to validateLogin method

public function validateLogin ($email, $password, General $General) {
   $encPassword = $General->encryptData($password);
}

Upvotes: 1

Related Questions