PHP分配类成员中的另一方法的值和访问的类内

问题描述 投票:-2回答:2

我遇到麻烦类成员设置的值在类中的另一种方法。我曾尝试使用__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;
    }


}
php class
2个回答
1
投票

你先的方法将无法正常工作$isType永远是false。因为它不是初始化,甚至当你与你的函数初始化isType($post)你给它trueas值。但是你在headJS()检查$this->isType ==‘U’所以总是假的。

对于第二种方法似乎一切都很好。我唯一的猜测是,你在呼唤HeadJS() isType($post)之前或$post的值总是比“U”不同


0
投票

你已经在$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;
}
}
© www.soinside.com 2019 - 2024. All rights reserved.