0

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

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

If you want to make sure that h is actually of that class you can use the getter and setter methods to ensure your always creating a new instance of the class.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.