Home > OS >  Method not working outside of the class it is in
Method not working outside of the class it is in

Time:05-09

Functions are not working due to undefined variables and I have no clue why that is. I think I just don't get the scope at which objects/classes work. Do I need to make a reference like $obj from which to call the functions? If so why is it not working in this example?

<?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();
?>

CodePudding user response:

$worker is undefined in checkTaxes()

If you want to use $worker in checkTaxes() or other functions, you should define $worker in class employee with private $worker = [];, just like $name and $salary.And after that, you can update it in populate() with $this->worker[0] = xxx;, and read it in checkTaxes() with $this->worker[$i]->getxxx.

  • Related