[英]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.