无法从一个函数访问变量到同一个类中的另一个函数

时间:2017-11-13 16:25:13

标签: php laravel function

我有一个班级,我正在定义一个变量

namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //I am assigning a new value to clientinfo variable
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
}

现在,在同一个班级中,我想将这个新的指定值用于$clientinfo变量,在另一个函数中complete()

namespace App\System\System;

class BoldSystem
{

    private $clientInfo;

    //The value stored to clientinfo should be accessed from complete function
    public function validateClient($firstname, $lastname, $email, $number)
    {
        $this->clientinfo = "firstname=".$firstname."&lastname=".$lastname."&email=".$email."&number=".$number;
        return 'test';
    }
    //I want to retrieve the value stored to clientinfo in this function
    public function complete()
    {
        return $this->clientinfo;
    }
}

当我调用complete()函数时,我得到null值,而我应该从$clientinfo函数中获取validateClient值。

我在这个单独的类中调用validateClient函数

class bookAppointment
{

    public function validate()
    {
        $business = new BoldSystem();
        $validate = $business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
    }

    public function book()
    {
        $business = new BoldSystem();
        //this returns null
        $book = $business->complete();
    }
}

1 个答案:

答案 0 :(得分:0)

好像你正在创建2个不同的实例(在bookAppointment类的validate和book方法中)!所以你应该清楚,为什么complete()返回null;)也许你应该为$ business使用一个类属性。

对您的系统了解不多,您可以将BoldSystem的实例注入bookAppointment的构造函数中,如下所示:

class bookAppointment {

    public $business;

    public function __construct(BoldSystem $boldSystem)
    {
        $this->business = $boldSystem;
    }

    public function validate()
    {
        $validate = $this->business->validateClient('test', 'test', 'test@gmail.com', '519998889898');
        // ... you further code
    }

    public function book()
    {
        // ...
        $book = $this->business->complete();
        // ...
    }
}

这只是在BoldSystem中保留bookAppointment的实例的示例。另一种选择是在bookAppointment属性的Boldsystem中创建setter / getter方法。

相关问题