2011-03-05 54 views
0

我需要與此類似在PHP:從結構類型轉換時,其被認爲是一種最好的做法端口簡單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); 
} 

回答

0

我創建了一個通用的PHP結構類,模擬C-結構,它可能對你有用。

代碼和例子在這裏: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; 
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

最簡單的使用方法值的對象。



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

使用getter和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); 
} 

+0

如果你想確保滿足h實際上是類,你可以使用getter和setter方法,以確保您始終創建的是該類的新實例。 – Dimentox 2011-03-05 22:47:32