在我的课堂上,我试图在除以外的函数中设置变量的值 __construct()
但我需要另一个函数中的变量值.
这是我尝试过的.但不能正常工作.
我希望打印getty images但我一无所获:(
<?php
class MyClass{
public $var;
public function __construct(){
$this->var;
}
public function setval(){
$this->var = 'getty Images';
}
public function printval(){
echo $this->var;
}
}
$test = new MyClass();
$test->printval();
Run Code Online (Sandbox Code Playgroud)
你的构造函数什么都不做,你需要调用它来做某事的方法.
class MyClass{
private $var;
public function __construct() {
// When the class is called, run the setVal() method
$this->setval('getty Images');
}
public function setval($val) {
$this->var = $val;
}
public function printval() {
echo $this->var;
}
}
$test = new MyClass();
$test->printval(); // Prints getty Images
Run Code Online (Sandbox Code Playgroud)