方法在 class 之外不起作用

Method not working outside of the class it is in

由于未定义的变量,函数无法运行,我不知道为什么会这样。我想我只是不了解 objects/classes 的工作范围。我是否需要像 $obj 这样的引用来调用函数?如果是这样,为什么它在这个例子中不起作用?

<?php
    class employee {

        // Properties
        public $name;
        public $salary = 0;
        
        // Methods
        function set_name($name) {
        $this->name = $name;

        }
        function get_name() {

        return $this->name;

        }
        function set_salary($salary) {
        $this->salary = $salary;

        }
        function get_salary() {

        return $this->salary;
        }
        
        function populate()
        {
            $worker = array();
            $worker[0] = new employee();
            $worker[0]->set_name('Linda');
            $worker[0]->set_salary(5800);
            $worker[1] = new employee();
            $worker[1]->set_name('Manuel');
            $worker[1]->set_salary(2750);
            $worker[2] = new employee();
            $worker[2]->set_name('Luis');
            $worker[2]->set_salary(3200);
            $worker[3] = new employee();
            $worker[3]->set_name('Carly');
            $worker[3]->set_salary(2999);
            $i = 0;
        }
    
        function checkTaxes()
        {
            while ($i < 4)
            {
                echo "Name: " . $worker[$i]->get_name();
                echo " - Salary: " . $worker[$i]->get_salary();
                
                if ($worker[$i]->get_salary() >= 3000)
                {
                    echo " - You have to pay taxes!<br><br>";
                }
                else
                {
                    echo " - You don't have to pay taxes!<br><br>";
                }
                $i++;
            }
        }
    }
    $obj = new employee;
    $obj->populate();
    $obj->checkTaxes();
?>

$workercheckTaxes()

中未定义

如果你想在checkTaxes()中使用$worker或者其他函数,你应该在classemployee中用private $worker = [];定义$worker,就像$name$salary。之后,您可以在 populate() 中使用 $this->worker[0] = xxx; 更新它,并在 checkTaxes() 中使用 $this->worker[$i]->getxxx 阅读它。