Objective:
I just tried to create linked list in php.
Challenges:
In php array is sufficient for most data types (simple array, multi-dimensional array and key-value associative array). But, i just tried using stdClass Object (pre-defined interfaces and class). Here, I created one stdClass with reference key and it reference to another class up to final and that final class reference key is null. Here I used reference key as reference variable. Once i started assigning reference value to this key it assigning new value to it and old one erased.
$a = new stdClass();
$a->name = "Trial";
$a->ref = null;
for($i=1;$i <= 10;$i++){
$b = new stdClass();
$b->name = 'Demo mj '.$i;
$b->ref = null;
if($a->ref === null ){
$a->ref = &$b;
}else{
$current = $a->ref;
while($current->ref !== null){
$current = $current->ref;
}
$current->ref = &$b;
}
}
print_r($a);
unset($current);
$current = $a->ref;
while($current->ref !== null){
echo $current->name.PHP_EOL;
$current = $current->ref;
}
Technology:
1. PHP 8.2
Variables in PHP;
1. Super global variables
2. Global variable
3.Function variable
4. Obscure variable names - ${'invalid-name'}
5. Reference variable $a = &$b
6. Variable variables -
$a = "hello";
$hello = "world";
echo $a." ".$$a;
result = hello world
Reference Variables:
Here, problem came from reference variable. I thought reference variables are reference that variable but, it shares value commonly and if change any one variable value to change that variable value. So, Once i assign value to that reference variable it assigned new value to that shared value (or change original value).That's why I lost old values. This technic is useful when we want to change original value within function scope.
Now changed that code and just record it in github repository. https://github.com/Aathiappan/LearningPHP/blob/main/DataStructure/LinkedList.php
Conclusion:
PHP reference variable not store variable memory address it shares value. It's also useful in function scope.
Ref: https://www.php.net/manual/en/language.references.arent.php
Comments
Post a Comment