Jump to content

[SOLVED] Class constants


barrywood

Recommended Posts

In my old non-OOP PHP coding I used defines and string arrays to create constants and string representations of them like this:

 

define ('_MYAPP_PAYSTAT_WAITING', 1);
define ('_MYAPP_PAYSTAT_PAID', 2);

$myapp_paystat_text[_MYAPP_PAYSTAT_WAITING] = 'waiting for payment';
$myapp_paystat_text[_MYAPP_PAYSTAT_PAID] = 'paid in full';

 

The downside is that I have to make sure I declare $myapp_paystat_text as a global variable in any functions that need to have access to the text representation.

 

I'd like to put this info into a class instead. Here's what I've come up with so far:

 

class MYAPP
{
const PAYSTAT_WAITING = 1;
const PAYSTAT_PAID = 2;

function PAYSTAT($dispCode) {
	switch ($dispCode) {
	case self:: PAYSTAT_WAITING: return ('Waiting');
	case self:: PAYSTAT_PAID: return ('Paid');
	}
}
}

 

Using this class I would access the constants like this:

 

if ($status == MYAPP::PAYSTAT_WAITING) echo "Your order status is currently ". MYAPP::PAYSTAT($status);

 

Does this seem like a reasonable way to approach this or is there a cleaner way?

Link to comment
Share on other sites

That's a good change. A note of caution as you start doing things the OO way: avoid classes with names like MYAPP that store all your application's data and behavior. OOP works best with lots of discrete little objects. Put these constants in a class called something like "Payment". Put that $status variable in there too, along with functions like getStatusText(). You'll have other objects like Order, Customer, and Product, and you'll have a devil of a time figuring out what code and what data goes where, but you'll end up with an OO application that's easier to understand and maintain.

Link to comment
Share on other sites

@mikesta707:

 

It appears that the functions are working fine as non-static functions without instantiating the class.

 

It also works declaring them "static function" and as "public static function".

 

I would think that public static would be the most accurate way to declare them so I'll be going with that.

 

Thanks for the input.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.