[英]PHP assign class member a value and access in another method within the class
我無法在類中的另一個方法中獲取類成員設置的值。 我嘗試使用__get
和__set
魔術方法、 getter
和setter
以及代碼中的另外兩種方法,但它們都不起作用。
我正在尋找的是,如果類型是U
,則應該使用 javascript 變量,否則不應該使用。
class UserRatings extends User {
private $postType; // string
public function headJS(){
// access postType value from getItem method
// this outputs nothing (blank)
if ($this->postType = 'U') {
# code...
}
}
public function getItem($post){
$this->postType = $post['data']['post_type'];
$markup = 'html markup to render the output';
return $this->postType;
}
public function isType($post)
{
if ($post == 'U') {
$this->isType = true;
}
return $this->isType;
}
}
class UserRatings extends User {
private $isType = false;
public function headJS(){
// even this doesnt't work too
if ($this->isType) {
# code...
}
}
public function getItem($post){
$markup = 'html markup to render the output';
$type = $post['data']['post_type'];
$this->isType($type);
}
public function isType($post)
{
if ($post == 'U') {
$this->isType = true;
}
return $this->isType;
}
}
您的第一種方法將不起作用,因為$isType
將始終為false
。 因為它沒有初始化,即使你用你的函數isType($post)
初始化它,你也給它true
作為一個值。 但是,如果$this->isType =='U'
則檢查您的headJS()
所以總是假的。
對於第二種方法,一切似乎都很好。 我唯一的猜測是,你在呼喚HeadJS()
之前isType($post)
或價值$post
總是比“U”不同
你錯過了$this->isType(type);
處的 $ 符號$this->isType(type);
.
你只需要調用$this->headJS();
在$this->isType = true;
class UserRatings extends User {
private $isType = false;
public function headJS(){
// even this doesnt't work too
if ($this->isType) {
# code...
}
}
public function getItem($post){
$markup = 'html markup to render the output';
$type = $post['data']['post_type'];
$this->isType($type);
}
public function isType($post)
{
if ($post == 'U') {
$this->isType = true;
$this->headJS();
}
return $this->isType;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.