[英]Access a property of an object inside a method of that class
我正在嘗試訪問該類方法中的對象的屬性。 這是我到目前為止所擁有的:
class Readout{
private $digits = array();
public function Readout($value) {
$length = strlen($value);
for ($n = 0; $n < $length; $n++) {
$digits[] = (int) $value[$n];
}
}
}
目標是能夠說$x = new Readout('12345')
,這會創建一個新的Readout
對象,其$digits
屬性設置為數組[1,2,3,4,5]
。
我似乎記得有一些問題在PHP中,在范圍$digits
可能並不里面可見Readout
,所以我嘗試更換$digits[] =
使用$this->$digits[] =
,但給了我一個語法錯誤。
好的語法是:
$this->digits[]
在您的情況下訪問類方法中的類屬性的正確語法是:
$this->digits[];
要創建一個設置為12345的新Readout對象,您必須實現如下所示的類:
class Readout {
private $digits = array();
public function __construct($value)
{
$length = strlen($value);
for ($n = 0; $n < $length; $n++) {
$this->digits[] = (int) $value[$n];
}
}
}
$x = new Readout('12345');
這是因為調用類中變量的正確方法取決於您是將它們作為靜態變量還是實例(非靜態)變量進行訪問。
class Readout{
private $digits = array();
...
}
$this->digits; //read/write this attribute from within the class
class Readout{
private static $digits = array();
...
}
self::$digits; //read/write this attribute from within the class
這也有效
<?php
class Readout{
public $digits = array();
public function Readout($value) {
$this->digits = implode(',',str_split($value));
}
}
$obj = new Readout(12345);
echo '['.$obj->digits.']';
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.