Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow operator in PHP vs C

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:

  • In C, -> 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.
  • In PHP, -> 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.

like image 334
Chris Happy Avatar asked Dec 08 '25 10:12

Chris Happy


1 Answers

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.

like image 73
ryantxr Avatar answered Dec 09 '25 22:12

ryantxr