将简单的C ++移植到PHP代码

时间:2011-03-05 22:24:18

标签: php c++ c

我需要在PHP中使用类似的东西:

struct MSG_HEAD
{
        unsigned char c;
        unsigned char size;
        unsigned char headcode;
};

struct GET_INFO
{
        struct MSG_HEAD h;
        unsigned char Type;
        unsigned short Port;
        char Name[50];
        unsigned short Code;
};

void Example(GET_INFO * msg)
{
    printf(msg->Name);
    printf(msg->Code);
}

3 个答案:

答案 0 :(得分:4)

class MSG_HEAD
{
    public $c;
    public $size;
    public $headcode;
}
class GET_INFO
{
    public $h;
    public $Type;
    public $Port;
    public $Name;
    public $Code;
}
function Example(GET_INFO $msg)
{
    echo $msg->Name;
    echo $msg->Code;
}

答案 1 :(得分:1)

使用值对象的最简单方法,从结构类型转换时被视为最佳实践。



class MSG_HEAD
{
    var $c, $size, $headcode;
}

class GET_INFO
{
    var $h, $Type, $Port, $Name, $Code;
    function __construct() {
        $this->h = new MSG_HEAD();
    }
}

function Example (GET_INFO $msg)
{
    print ($msg->Name);
    print ($msg->Code);
}

使用更高级的Getters和setter但应该允许它更像结构



class MSG_HEAD
{
    protected $c;
    protected $size;
    protected $headcode;


    function __get($prop) {
        return $this->$prop;
    }

    function __set($prop, $val) {
        $this->$prop = $val;
    }
}

class GET_INFO
{
    protected $MSG_HEAD;
    protected $Type;
    protected $Port;
    protected $Name;
    protected $Code;
    function __construct() {
        $this->MSG_HEAD = new MSG_HEAD();
    }

    function __get($prop) {
        return $this->$prop;
    }

    function __set($prop, $val) {
        $this->$prop = $val;
    }
}

function Example (GET_INFO $msg)
{
    print ($msg->Name);
    print ($msg->Code);
}

答案 2 :(得分:0)

我创建了一个通用的php Struct类来模拟c-structs,它可能对你有用。

此处的代码和示例:http://bran.name/dump/php-struct

使用示例:

// define a 'coordinates' struct with 3 properties
$coords = Struct::factory('degree', 'minute', 'pole');

// create 2 latitude/longitude numbers
$lat = $coords->create(35, 40, 'N');
$lng = $coords->create(139, 45, 'E');

// use the different values by name
echo $lat->degree . '° ' . $lat->minute . "' " . $lat->pole;