Irakli Tchitadze Irakli Tchitadze - 3 days ago 5
PHP Question

Need to rewrite C++ code to PHP

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.

Answer

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.

Comments