需要将C 代码重写为PHP

Need to rewrite C++ code to PHP

本文关键字:重写 PHP 代码      更新时间:2023-10-16

我有一个任务。我需要将C 代码重写为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;
}

编译器的返回是0 2 1 0。我已经在PHP中重写了此代码:

<?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";

此代码的返回是:1 2 0 0。我知道php,我知道为什么它返回了这个值。我需要了解C 结构中的工作原理以及为什么[0] 全球增量。请帮助在PHP上重写此代码。我也知道,PHP中没有结构。

之间的差异
function f($st, $r_st, $a, $n)
void f(Structure st, Structure& r_st, int a[], int n)

在C 中,您始终指定,按值或引用通过,但是在PHP中有一些预定义的规则。

修复了第1个输出

c 部分: st是按值和原始值传递的,您通过此处通过的原始值不会更改。r_st通过引用传递,然后更改原始值。

php部分:两个参数都是通过引用传递的,因为它们是类。

简单的修复程序是克隆对象st并将其传递给函数到模仿C 通过逐副复制,或在功能中克隆它。


修复了第三次输出

在C int a[]中以指针的形式传递,因此,原始值已更改,但是在PHP中,它按值传递,并且在外部不变。

简单的修复程序将是 &$a而不是 $a在功能参数中。

ps。我是C 开发人员,因此,PHP部分在术语中可能不准确。

您传递的ss0ss1变量是该功能的对象访问者。请参阅对象和参考

传递的变量是按值。参见参考

通过

请帮助在php上重写此代码。

这样做

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++;
}

阅读有关PHP中的参考文献。我不是C 开发。

http://php.net/manual/en/language.oop5.cloning.php