Jump to content

Implications of passing by reference


NotionCommotion

Recommended Posts

If getValue is given a path which doesn't exist, I can use the isset check to return null.

I can also use the uncommitted $tmp =&$tmp[$key];.  Why does this prevent an undefined index warning?

 

    public function getValue(string $path) {
        $path=explode('.', $path);
        $tmp=$this->config;
        foreach($path as $key) {
            //if(!isset($tmp[$key])) return null;
            //$tmp =$tmp[$key];
            $tmp =&$tmp[$key];
        }
        return $tmp;
    }


 

Link to comment
Share on other sites

Asking for a reference is considered a writing context.  If the variable doesn't exist, it is created with a NULL value.

Since you're overwriting $tmp each time, you don't notice any issues.  If you were not overwriting it you'd notice those keys being created as the loop progresses. 

I use this when trying to group results from a query easily.  For example, say I had a query that returned students and their enrolled courses and wanted to end up with an array with the list of students, and their enrollments by session.  I'd do something like:

	$result = [];
foreach ($stmt as $row){
    $studentId = $row['studentId'];
    $sessionId = $row['sessionId'];
    $courseId = $row['courseId'];
	    $student = &$result[$studentId];
    if (!$student){
        //Haven't seen student yet
        $student = [
            'fistName' => $row['studentFirstname']
            , 'lastName' => $row['studentLastname']
            , 'id' => $studentId
            , 'sessionList' => []
        ];
    }
	    $session = &$student['sessionList'][$sessionId];
    if (!$session){
        //Haven't seen session yet
        $session = [
            'name' => $row['sessionName']
            , 'id' => $sessionId
            , 'courseList' => []
        ];
    }
	    //Assume no course duplicates.
    $course = &$session['courseList'][$courseId];
    $course = [
        'name' => $row['courseName']
        , 'id' => $courseId
    ];
}
	

The code is simpler due to not having to check if keys exist or not by using isset() in each step.  Using the reference will create the key and I can do a simple if to see if it was newly created or already existed.  It also make a nice alias so at the end I can just do $session['courseList'][$courseId] instead of having to do $result[$studentId]['sessionList'][$sessionId']['courseList'][$courseId].

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.