1

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

0

4 Answers 4

1

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
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

br3nt : your solution is easy to read and understand. it's also clean. I like it.
Sometimes PHP can be elegant 😛
1

You can inject class General to validateLogin method

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

Comments

1

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);
  }
}

Comments

1

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
    }    

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.