2011-03-05 51 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