Page 1 of 1

Using classes instead of C/C++ style structs?

Posted: Sat Feb 24, 2007 4:36 am
by mjseaden
Hi,

This isn't so much a problem but (perhaps) a solution.

One of the downfalls of PHP is that it does not allow structs, for example:

Code: Select all

struct REC_PRODUCT
{
   TCHAR szProductID[PRODUCTID_SZLEN];
   int64 nSalesPrice;
   int64 nCostPrice;
   TCHAR szSupplierID[SUPPLIERID_SZLEN];
};
You can then pass these structures between functions after popluating them with data. I don't like associative arrays, because they don't behave in exactly the same way. Wouldn't a solution to the above problem however be something like

Code: Select all

class REC_PRODUCT
{
   char szProductID[PRODUCTID_SZSLEN];
   int nSalesPrice;
   int nCostPrice;
   char szSupplierID[SUPPLIERID_SZLEN];
}
Which you could then pass between functions like a C/C++ style struct?

Just a thought.

Posted: Sat Feb 24, 2007 8:33 am
by Chris Corbyn
This is commonly done yes :) In C++ you can pretty much abandon structs and just use classes too...

Posted: Sat Feb 24, 2007 10:42 am
by feyd
Last I checked, C++ considered structs classes, but with different default permissions. PHP's default permissions for classes is actually the same as using structs for classes in C++.

Posted: Sat Feb 24, 2007 11:46 am
by Chris Corbyn
In C++, structs are classes yes. They just cannot contain methods, and the access control is public in structs, whereas in classes it's private by default. They both use the same memory space as far I know.

Posted: Sat Feb 24, 2007 12:12 pm
by Mordred
d11wtq wrote:They just cannot contain methods
They can.

In C++ they are basically recycled syntactic sugar, left for backward compatibility with C.


The correct php code would be:

Code: Select all

class REC_PRODUCT 
{ 
   var $szProductID;
   var  $nSalesPrice; 
   var  $nCostPrice; 
   var  $szSupplierID;
}