Pointers in PHP

<?php

// PHP supports references, which are similar to pointers in some ways.
// We'll show how references work in contrast to values with
// 2 functions: `zeroval` and `zeroref`.

// `zeroval` has an integer parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `$ival` distinct
// from the one in the calling function.
function zeroval($ival) {
    $ival = 0;
}

// `zeroref` in contrast has a `&$iref` parameter, meaning
// that it takes a reference to an integer. Assigning a value
// to a reference changes the value of the original variable.
function zeroref(&$iref) {
    $iref = 0;
}

function main() {
    $i = 1;
    echo "initial: $i\n";

    zeroval($i);
    echo "zeroval: $i\n";

    // The `&$i` syntax gives a reference to `$i`.
    zeroref($i);
    echo "zeroref: $i\n";

    // In PHP, we can't print the memory address directly,
    // but we can demonstrate that two variables reference the same value.
    $j = &$i;
    $i = 2;
    echo "reference demonstration: i = $i, j = $j\n";
}

main();
$ php pointers.php
initial: 1
zeroval: 1
zeroref: 0
reference demonstration: i = 2, j = 2

In this PHP example, we’ve translated the concept of pointers to references, which is the closest equivalent in PHP. Here are the key differences and similarities:

  1. PHP doesn’t have explicit pointers, but it does have references which serve a similar purpose.

  2. Instead of using * to declare a pointer, PHP uses & before a parameter to indicate it should be passed by reference.

  3. In the zeroref function (equivalent to zeroptr in the Go example), we don’t need to dereference the reference. We can directly assign to it.

  4. PHP doesn’t allow direct access to memory addresses, so we can’t print a pointer value like in the Go example. Instead, we’ve added a demonstration of how references work by showing that two variables can reference the same value.

  5. The zeroval function works the same way in PHP as it does in Go, not modifying the original variable.

  6. The zeroref function (like zeroptr in Go) does modify the original variable because it receives a reference.

This example demonstrates how PHP handles references, which serve a similar purpose to pointers in allowing functions to modify variables from the calling scope.