我有以下代码,但我无法打印对象名称:
<?php
class persons {
public function people(){ //__construct OR persons to class define constructor
$this->name="pepe";
}
public function print_1(){
echo $this->name;
echo '<br>';
}
}
$per1=new persons();
$per1->print_1();
?>
答案 0 :(得分:1)
您的init
函数永远不会执行,因此永远不会设置名称
如果您打算使用构造函数you need to name it __construct
。
(关于保留的print
关键字的其他错误也适用。)
答案 1 :(得分:0)
假设您有致命错误,因为print
是保留关键字,您不能使用类method
名称,请使用其他名称,请参阅下文
<?php
class persons {
var $name = "";
public function people(){
$this->name="pepe";
}
public function print_1(){
echo $this->name;
echo '<br>';
}
}
$per1=new persons();
$per1->people();
$per1->print_1();
?>
由于@deceze在评论__construct()
或ClassName
方法中提及类构造以初始化值
答案 2 :(得分:-1)
您需要在对象中定义$name
。您还有print()
我认为您无法使用。你必须做出类似_print
的其他内容。
<?php
class persons
{
public $name;
public function init(){
$this->name = "pepe";
}
public function _print(){
echo $this->name;
echo '<br>';
}
}
$per1 = new persons();
// If you don't define your name in a class you use (ie. you should define it in your $this->_print()), you can define it outside
// It's not the greatest solution. but it will work.
$per1->name = 'pepe';
$per1->_print(); ?>
您还可以在init()
内定义_print()
,如下所示:
<?php
class persons
{
public $name;
public function init(){
$this->name = "pepe";
}
public function _print(){
$this->init();
echo $this->name;
echo '<br>';
}
}
$per1 = new persons();
$per1->_print(); ?>