如何从php中同一个类中的另一个函数调用公共函数中的变量

时间:2015-12-12 23:30:08

标签: php class oop

<?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()函数中写一个$ dollar,但它给了我一个错误 并且在这段代码中,它甚至没有显示我尝试使用的内容 &#34;类名:: function name() - &gt;颜色;&#34;也没有工作 我尝试了很多我在这里找到的东西,但没有一个真的对我有用

1 个答案:

答案 0 :(得分:0)

你很亲密......

<?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类和对象。

相关问题