<?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(( 函数中写一个 $ 美元,但它给了我一个错误在此代码中,它甚至没有显示我什至尝试使用的任何内容"类名 :: 函数名 ((-> 颜色;" 也不起作用我尝试了很多我在这里找到的东西,但没有一个真正适合我
你很接近...
<?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 类和对象的 php.net。