我对OOP很新,所以我遇到了一个问题
我创建了一个班级
/modules/template/02.02.01.10-SNAPSHOT/templates/base/navbar2/navbarlinks-lang
然后是一个对象
class Lesson {
function Lesson( $title, $sample ) {
$this->title = $title;
$this->sample = $sample;
}
}
当我试图访问对象的属性时
$title = 'title';
$sample = false;
$lesson = new Lesson( $title, $sample );
我收到此错误消息
"脚本试图执行方法或访问某个属性 不完整的对象..."
答案 0 :(得分:0)
您的属性尚未定义。尝试在类声明的顶部添加它们。
class Lesson {
public $title = '';
public $sample = '';
public function Lesson( $title, $sample ) {
$this->title = $title;
$this->sample = $sample;
}
}
构造函数语法也取决于php的含义。如果你是> 5.3.3你应该使用__construct()
class Lesson {
public $title = '';
public $sample = '';
function __construct( $title, $sample ) {
$this->title = $title;
$this->sample = $sample;
}
}
答案 1 :(得分:0)
您需要将function Lesson
更改为function __construct
才能在创建时传递这些值。
class Lesson {
function __construct( $title, $sample ) {
$this->title = $title;
$this->sample = $sample;
}
}
否则,您必须像这样创建它:
$lesson = new Lesson();
$lesson->Lesson($title, $sample);
echo $lesson->title;