我有两个类; userFunction
和userDatabase
:
class userDatabase {
protected $database = 'btc.db';
protected $short;
protected $salt;
function __construct(){
$this->short = $this->salt = bin2hex(random_bytes(6));
}
}
class userFunction extends userDatabase {
function __construct(){
$this->database.PHP_EOL;
$this->short.PHP_EOL;
$this->salt.PHP_EOL;
}
}
$r = new userFunction;
var_dump($r);
输出如下:
object(userFunction)#1 (3) {
["database":protected]=>
string(6) "btc.db"
["short":protected]=>
NULL
["salt":protected]=>
NULL
}
这不完全是我所期望的。大概我设置了$this->short
和$this->salt
,以从二进制数据生成随机的 6 个字符的随机十六进制盐。我扩展了 userDatabase
类以将变量继承到userFunction
我希望能够在userFunction
__construct()
内通过 $this->salt
和 $this->short
调用这些变量。但是,变量返回为 NULL
。
我一直在寻找为什么会这样的想法,但我似乎无法正确表述查询,因为我真的不确定这里发生了什么。这似乎是一个相关的问题,但我不完全确定。具体来说,是否有可能完成我试图以这种特定方式做的事情?每个类中的 $this->salt
和$this->short
实例是否相同,还是它们都不同?我将如何解决我的NULL
问题,在这里?
我感谢你的帮助。
当您重写子项中的__construct
(或任何其他方法)时,不会调用父级的方法 - 除非您明确这样做。
class userFunction extends userDatabase {
function __construct(){
parent::__construct();
$this->database.PHP_EOL;
$this->short.PHP_EOL;
$this->salt.PHP_EOL;
}
}