I have a task. I need to rewrite C++ code to PHP.
#include <iostream>
using namespace std;
struct Structure {
int x;
};
void f(Structure st, Structure& r_st, int a[], int n) {
st.x++;
r_st.x++;
a[0]++;
n++;
}
int main(int argc, const char * argv[]) {
Structure ss0 = {0};
Structure ss1 = {1};
int ia[] = {0};
int m = 0;
f(ss0, ss1, ia, m);
cout << ss0.x << " "
<< ss1.x << " "
<< ia[0] << " "
<< m << endl;
return 0;
}
return of a compiler is 0 2 1 0. I have rewrote this code in PHP like this:
<?php
class Structure {
public function __construct($x) {
$this->x = $x;
}
public $x;
}
function f($st, $r_st, $a, $n) {
$st->x++;
$r_st->x++;
$a[0]++;
$n++;
}
$ss0 = new Structure(0);
$ss1 = new Structure(1);
$ia = [0];
$m = 0;
f($ss0, $ss1, $ia, $m);
echo $ss0->x . " "
. $ss1->x . " "
. $ia[0] . " "
. $m . "\n";
return of this code is: 1 2 0 0. I know PHP and I know why it is returning this values. I need to understand how in C++ struct works and why a[0]++ is globally incremented. Please help to rewrite this code on PHP. I also know than there is no struct in PHP.
int a[]is the same asint* a, so the parameter is passed as a pointer.a[0]++increments the object pointed to, not a local copy.