Reputation: 2077
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.
Upvotes: 1
Views: 133
Reputation: 4493
Difference between:
function f($st, $r_st, $a, $n)
void f(Structure st, Structure& r_st, int a[], int n)
in C++ you always specify, pass by value or by reference, but in PHP there are some pre-defined rules.
Fix for 1st output
C++ part: st
is passed by value, and original value, which you pass here is not changed. r_st
is passed by reference, and original value is changed.
PHP part: both arguments are passed by reference, since they are classes.
Simple fix there is to clone object st
and pass it to function to mimic C++ pass-by-copy, or clone it inside function.
Fix for 3rd output
in C++ int a[]
is passed as pointer, so, original value is changed, but in PHP it is passed by value, and it is unchanged outside.
Simple fix for it would be &$a
instead of $a
in function parameters.
PS. I'm C++ developer, so, PHP part can be inaccurate in terminology.
Upvotes: 3
Reputation: 3795
Please help to rewrite this code on PHP.
Do it like this
function f($st, $r_st, &$a, $n) {
$st= clone $st; #clone to get a real copy, not a refer
$st->x++;
$r_st->x++;
$a[0]++; #&$a to simulate ia[] (use as reference)
$n++;
}
Read about references in PHP. I'm not a C++ dev.
http://php.net/manual/en/language.oop5.cloning.php
Upvotes: 0
Reputation: 783
The ss0
and ss1
variables you are passing in are by object accessors to that function. See Objects and references
The variables passed in are by value. See Passing by Reference
Upvotes: 1