[英]how to call a variable in a public function from another function within the same class in php
<?php
class Pen
{
public $color;
public function clr()
{
$this->color = "Red";
}
public function write()
{
echo $this->color; //if i write $ before color it gives me an error
}
}
$a = new Pen();
$a->write();
?>
我试图在write()函数中写一个$美元,但是它给了我一个错误,并且在此代码中它什么也没显示,我什至试图使用“类名::函数名()-> color;” 也没有用,我尝试了很多我在这里找到的东西,但没有一个对我有用
你很近...
<?php
class Pen
{
public $color;
// Constructor, this is called when you do a new
public function __construct($color = null)
{
// Call setColor to set the color
$this->setColor($color);
}
// Method to set the color
public function setColor($color) {
$this->color = $color;
}
// Write out the color
public function write()
{
echo $this->color;
}
}
// Construct a new red pen
$a = new Pen('red');
// Write with it
$a->write();
// Change the color to blue
$a->setColor('blue');
// Write with it
$a->write();
?>
花一些时间在php.net上阅读有关PHP类和对象的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.