Question

I have a basic knowledge about PHP but I want to learn how to use classes to make my program OOP, so I tried just a simple class that will generate a hash for the password and I'm using bcrypt for hashing.

So far the code i've written is this:

PasswordHash.php

class PasswordHash {
    public static function generate_bcrypt($user_password) {
        return $this->password = password_hash($user_password, PASSWORD_DEFAULT);
    }
}

PasswordHash.php is in the classes folder.

index.php

    spl_autoload_register(function($class){
        require_once 'classes/' . $class . '.php';
    });

    $password = 'mypassword';

    echo $hashed = PasswordHash::generate_bcrypt($password);

When I check if it is working, nothing happens. can someone help me with this? am I missing something on my code? Thanks in advance.

Était-ce utile?

La solution

To call it as an object:

class PasswordHash {
        public function generate_bcrypt($user_password) {
            return password_hash($user_password, PASSWORD_DEFAULT);
        }
}

$password = 'password';
$passwordhash = new PasswordHash();
echo $passwordhash->generate_bcrypt($password);

To call it using the static method

class PasswordHash {
        public static function generate_bcrypt($user_password) {
            return password_hash($user_password, PASSWORD_DEFAULT);
        }
}

$password = 'password';
echo PasswordHash::generate_bcrypt($password);

You'll need to adapt this to fit the separation of your class files, but you can get the general idea from the examples.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top