简体   繁体   中英

Calling function inside a function in controller

Tried to call a function inside a function.

It does not return value from the second function.

When the while loop breaks the function will return a value but it does not return array value.

<?php
function getdetails()
{
    $parentarray=array();
    $parentsid=2;
    array_push($parentarray,$parentsid);
    $getallparents=self::getparents($parentarray,$parentsid);
}

function getparents($parentarray,$parentsid)
{
    $this->db->select('*');
    $this->db->from('users');
    $this->db->where('user_id',$parentsid);
    $query = $this->db->get();
    $results = $query->result();
    $parentsid=$results[0]->parent_id;
    $var="true";
    while ($var=="true") {
        array_push($parentarray,$results);

        if($parentsid==0)
        {
            $var="false";
            $returnvalue=$parentarray;
        }
        else
        {
            $var="true";
            self::getparents($parentarray,$parentsid);
        }
    }
 return $returnvalue;
}
?>

Update

$returnvalue=$parentarray;

With

return $parentarray;

Final code will look like this.

function getparents($parentarray, $parentsid)
    {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('user_id', $parentsid);
        $query = $this->db->get();
        $results = $query->result();
        $parentsid = $results[0]->parent_id;
        $var = true;
        while ($var == true) {
            array_push($parentarray, $results);

            if ($parentsid == 0) {
                $var = false;
                return $parentarray;
            } else {
                $var = true;
                self::getparents($parentarray, $parentsid);
            }
        }
    }

Good luck :)

because you are not returning any value from the second function. you are just assigning your value to a new variable. use return $parentarray; instead of $returnvalue=$parentarray; in your second function.

You are calling an instance method with static notion.

Change all occurrences of self::getparents to $this->getparents .

BTW, why the functional-programming tag? It does not have anything to do with that topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM