我在这里和PHP都很新.
我想知道在他的参数中在另一个类构造函数中实例化一个类的正确方法是什么.
(我在底部有一些狗屎测试)
class CryptoControl {
public $helper;
public $keyValues;
public function __construct ($primo1, $primo2, $message) {
$this->helper = new MathHelper();
$this->keyValues = new KeyValues($primo1, $primo2, $message);
}
public function criptografa_descriptografa_simetrica() {
$message = $keyValues->getMessage();
echo "Texto original: " . $message . "\n";
echo "Chave criptografada: " . base64_encode($message) . "\n";
$message_criptografada = base64_encode($message);
echo "Chave descriptografada: " . base64_decode($message_criptografada) . "\n";
}
}
$exec = new CryptoControl(17, 41, "TURING");
$resposta = $exec->criptografa_descriptografa_simetrica();
echo $resposta;
这就是我想要实例化的类:
class KeyValues {
public $numeroPrimo_1;
public $numeroPrimo_2;
public $message;
public function KeyValues ($primo1, $primo2, $message) {
$this->numeroPrimo_1 = $primo1;
$this->numeroPrimo_2 = $primo2;
$this->message = $message;
}
#getters and setters
}
那是我得到的错误……
PHP注意:未定义的变量:第72行/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php中的keyValues
PHP致命错误:在第72行的/home/rodolfolottin/gitrepositories/Crypto/CryptoControl.php中的非对象上调用成员函数getMessage()
谢谢你的帮助…
解决方法:
更改以下行
$message = $keyValues->getMessage();
至
$message = $this->keyValues->getMessage();
类中方法内的$keyValues引用局部变量.当您使用$this关键字访问时,它会引用该类的对象的属性.
标签:php,oop
来源: https://codeday.me/bug/20190623/1274701.html