簡體   English   中英

PHP 為類成員分配一個值並在類中的另一個方法中訪問

[英]PHP assign class member a value and access in another method within the class

我無法在類中的另一個方法中獲取類成員設置的值。 我嘗試使用__get__set魔術方法、 gettersetter以及代碼中的另外兩種方法,但它們都不起作用。

我正在尋找的是,如果類型是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM