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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

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

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

This is commonly done yes :) In C++ you can pretty much abandon structs and just use classes too...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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++.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

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