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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容