dongmuyuan3046 2015-12-12 23:30
浏览 95
已采纳

如何从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();  
?>

i tried to write an $ dollar in the write() function but it gives me an error and in this code it shows nothing i even tried to use "class name :: function name ()-> color ;" didn't work either i tried a lot of things that i found here but none of them really worked for me

  • 写回答

1条回答 默认 最新

  • dongqucheng3851 2015-12-12 23:35
    关注

    You are close ...

    <?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();
    ?>
    

    Take some time to read about PHP classes and objects at php.net.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法