I am a PHP programmer trying to learn more of the theory behind PHP, but having trouble connecting the dots between PHP and C. For example, is the arrow operator exactly the same in PHP and C?
Here's what I came up when I researched it:
-> is just an alias, a->b is the same as (*a).b. The arrow operator is just dereferencing a pointer so you interact with the address variable.-> is a reference. It "references the attributes of an instantiated object" (Unknown). But is that the same thing as C?Note: Today, I learned what pointers are in C.
In PHP, -> is used to access members of a class. C does not have classes.
The closest thing is a struct.
In PHP
class Animal {
public $color;
public $age;
}
$fido = new Animal;
$fido->color = 'white';
$fido->age = 3;
$kitty = new Animal;
$kitty->color = 'brown';
$kitty->age = 5;
// output
echo 'Fido is ' . $fido->color . "age=". $fido->age . "\n";
echo 'Kitty is ' . $kitty->color . "age=". $kitty->age . "\n";
Output is:
Fido is white age=3
Kitty is brown age=5
You can do something similar in C using structs. It's a bit more involved.
Excuse my C. It's quite rusty
struct Animal {
int age;
char color[50];
};
int size = sizeof(struct Animal);
struct Animal * fido = malloc(size);
struct Animal * kitty = malloc(size);
fido->age = 3;
strcpy(fido->color, "white");
kitty->age = 5;
strcpy(kitty->color, "brown");
printf("Fido is %s age=%d\n", fido->color, fido->age);
printf("Kitty is %s age=%d\n", kitty->color, fido->age);
Unless you really want to get into the underlying details, don't overthink PHP references. What that means is that they don't pass around the actual values when doing function calls etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With