PHP OOP:如何在同一个类的另一个方法中使用一个方法


PHP OOP: How to use a method in another method of the same class?

如何在同一类的另一个方法中使用方法?我有一个getName()方法,如果name字段为空或不为空,它将返回,如果它为空,则返回值将显示在文本字段旁边。

class UserInfo extends TextInput{
    public function setName($name){ 
        $this->name = $name;
    }
    public function getName(){
        if($isEmpty = Validate::isEmpty($this->name)){
            return "Name" . $isEmpty;
        }
        else{
            return $this->name;
        }
    }
    public function createUserInfo(){
        echo $this->createInput('NAME' ,'text', 'name'); //create text input for name
        getName(); //if 'submit', return the value of getname 
    }
}

您可以尝试以下createUserInfo方法,就像您使用$this关键字使用的properties/variables一样,但唯一不同的是,当调用method/function时使用():

$this->getName();

$this为当前object

很简单,像这样:

$UserInfo_class = new UserInfo();
$UserInfo_class->setsetName('Name');
$UserInfo_class->getName('Name');

但是你在你的类中有这个。也许这就是你的问题所在?

public function createUserInfo(){
    echo $this->createInput('NAME' ,'text', 'name'); //create text input for name
    getName(); //if 'submit', return the value of getname 
}

应该是;注意$this->:

public function createUserInfo(){
    echo $this->createInput('NAME' ,'text', 'name'); //create text input for name
    return $this->getName(); //if 'submit', return the value of get name 
}