Tomas
Tomas

Reputation: 47

Port simple C++ to PHP code

I need something similar to this in 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);
}

Upvotes: 0

Views: 776

Answers (3)

Bran van der Meer
Bran van der Meer

Reputation: 771

I created a general purpose php Struct class, to emulate c-structs, it might be useful to you.

Code and examples here: http://bran.name/dump/php-struct

Example usage:

// 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;

Upvotes: 0

Dimentox
Dimentox

Reputation: 189

Simplest method using value objects which is considered a best practice when converting from a struct type.



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

Using Getters and setters which is a bit more advanced but should allow for it to act more like a struct



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

Upvotes: 1

Vilx-
Vilx-

Reputation: 106902

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

Upvotes: 4

Related Questions