Jump to content

Can have Text in Switch?


doubledee

Recommended Posts

The first question that comes to mind: did you try it? Are you afraid a syntax/runtime error may crash your computer?

 

A small test-case:

switch ('will the switch correctly handle this string?') {
  case 'will the switch correctly handle this string?':
    echo 'yes';
    break;
  case 'oh NOES!!':
    echo 'no';
    break;
  default:
    echo 'at this point you should start running...';
    break;
}

Link to comment
Share on other sites

The first question that comes to mind: did you try it?

 

Yes, I did try it.  That doesn't mean what I have is correct...  ::)

 

 

Debbie

 

 

 

 

So do us all a favour and post the relevant code along with a description of what expect to happen and what *is* actually happening.

Link to comment
Share on other sites

You might need to post an example, it's not real clear what your doing.

 

A switch can only check a single variable or constant is equal to a series of values.

 

Here is what I have...

switch ($resultsCode){
	case 'PASSWORD_USER_NOT_LOGGED_IN':
	// Some message...
	break;

	case 'PASSWORD_NEW_PASSWORD_SET':
	// Some message...
	break;

	case 'PASSWORD_NEW_PASSWORD_FAILED':
	// Some message...
	break;

	case 'PASSWORD_INVALID_EMAIL':
	// Some message...
	break;

	default:
	// Default Error.
	// Some message...
	break;
}

 

It seems to be working, but I am not as comfortable with Switches because of the "Loosing Comparison" thing...

 

 

Debbie

 

Link to comment
Share on other sites

Cool, so it's working? What is the question again then?

 

The question was and still is...

 

Can you use a Switch() statement to effectively check for codes like this...

PASSWORD_USER_NOT_LOGGED_IN

 

I have about 5 codes that need to be checked in order to display different outcome messages...

 

Would it be better to use an IF-THEN-ELSEIF instead?

 

The code I posted seems to work, but I am not confident in it, and could use some expert advice.

 

 

Debbie

 

 

Link to comment
Share on other sites

If you have one variable and want to test against several possibilities, a switch is generally the way to go.

 

I'm not sure what your concern is with "loose comparsion".  Unless all your if statements are comparing using the === or !== operators then your performing a loose comparsion there as well and there's no difference between them and a switch, other than a switch being cleaner and easier to read.

 

There's nothing wrong with a loose comparison generally.  Only in a few instances might it cause a problem.

 

 

Link to comment
Share on other sites

If you have one variable and want to test against several possibilities, a switch is generally the way to go.

 

I'm not sure what your concern is with "loose comparsion".  Unless all your if statements are comparing using the === or !== operators then your performing a loose comparsion there as well and there's no difference between them and a switch, other than a switch being cleaner and easier to read.

 

There's nothing wrong with a loose comparison generally.  Only in a few instances might it cause a problem.

 

Can you explain to me what exactly a "Loose Comparison" means?

 

I just recall many eons ago in college that Switch/Case was seen as weak because things could slip through the comparison that wouldn't with an IF-THEN-ELSE.  (Sorry I don't have any examples.)

 

 

I know I have also seen people using === in the past but didn't know why.  (Maybe that is related to this topic?)

 

Thanks,

 

 

Debbie

 

Link to comment
Share on other sites

A good example is with a boolean. If you say "if $var == true", then if $var is actually 1 (integer) then it will pass (since 1 evaluates to true). If you say "if $var === true" then you are saying if $var is a boolean, and is true.

 

EDIT: Actually, if you do "if $var == true" then if $var is equal to ANYTHING (except null, or 0) then it will be true.

Link to comment
Share on other sites

First off, there is nothing weak about a switch statement.  The rule of thumb is that if you have a single variable that can have a variety of values, and you need to branch on those values, a switch is always going to be clearer both to you, and to anyone reading your code in the future.  It is always going to be clearer than a big nested if elseif elseif elseif etc..  At the end of the day, the code generated is going to be exactly the same for either construct.

 

PHP is a loosely typed language.  This means that while there are variable types you do not need to declare them, and php will typecast between types without you having to explicity cast a value from one type to another.  In most cases this is a huge convenience and advantage of the language.  PHP figures out what you want to do, and does the right thing using the operator involved.  So I can have 2 string values, that both happen to be integers, and multiply them together and use the result. 

 

So in the case of comparison operators like the equality operator ("==") there is an option to check both equality AND that the types of the variables match.  As scootsah had in his example this most often is a concern with boolean values. 

 

Here's a typical example (not that I would recommend this) but frequently people write database functions or methods that return values.  Let's say you have a function that takes a name, and then returns the number of people in the database who have that lastname.

 

This might be accomplished using a SELECT count(*) FROM... or mysql_num_rows().  In either case a perfectly valid return value would be '0'.  This means that the query ran, but there were no rows matched for that lastname.

 

Now lets say that same function has error checking in case the query fails:

 

$count = getPersonCount($lastname);
if ($count == false) {
  // Display database error message/log error.
  echo "Database error:  the Administrator has been alerted."; 
} else {
   echo "We found $count people with $lastname";
}

 

The problem with this code is that it is going to display the database error message, even when the query runs ok, but there are no people matched.  This is because the "0" integer return gets typecast to a boolean, which is equivalent to false.

 

Let's assume that in the getPersonCount() function, when an actual database error occurs, the function explicitly will return false, otherwise it will return the count.  We can fix the comparison and have it work correctly by using:

 

$count = getPersonCount($lastname);
if ($count === false) {
  // Display database error message/log error.
  echo "Database error:  the Administrator has been alerted."; 
} else {
   echo "We found $count people with $lastname";
}

 

And now when the query returns 0 as the result, it will actually display "We found 0 people...." where it would never display that using the == comparison.

Link to comment
Share on other sites

Well technically a switch statement in most languages is a integer only function. Being dynamically typed PHP threw this into the mixed function group.

 

A "Cleaner" way would be to use a Factory design pattern if you don't want to make multiple comparisons. e.g.

 

<?php

$myThing = MyInit::init( $_POST );

$myThing->doSomthing();

class MyInit()
{
public static function init( $postedVars )
{
	$initClass = sprintf( 'Thing%s', $postedVars[ 'letter' ] );
	if( class_exists( $initClass ) )
		return new $initClass();
}

// Factories shouldn't be instantiated
private function __construct(){}
}

abstract class DoThings
{
abstract public function doSomething();
}

class ThingA extends DoThings
{
function doSomething()
{
	// Thing A
}
}

class ThingB extends DoThings
{
function doSomething()
{
	// Thing A
}
}

class ThingC extends DoThings
{
function doSomething()
{
	// Thing A
}
}

Link to comment
Share on other sites

That is not at all what the Factory pattern is for, and is in no way cleaner than a simple switch statement.

 

Please elaborate why a factory pattern is not cleaner than a switch statement. As procedural code is less maintainable than object orientated code. If a switch statement reaches 100 clauses it's a complete mess and a total joke, where a factory design pattern maintains its composure of cleanliness and maintainability.

 

Also, if a factory pattern is not for use of variable object representation please tell me what it's for?

Link to comment
Share on other sites

A Factory pattern is for object creation. It is not an "OOP Switch method".

 

And 100 repeated classes called "ThingA", "ThingB" is better how exactly?

 

Well if you have ever worked in a development team where you have masses of procedural files making changes becomes "messy" and if unique functionality is required you have one hell of a bloated switch statement.

 

Basically heading towards Spaghetti Code or a Loop-switch sequence. I'm not saying it's at that state but going down this path usually ends up this way.

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.