1

Possible Duplicate:
PHP and Enums

I want to create a function with several parameters that one of them has several constant variable. for example:

<?php
function print($str, $num){...}
.
.
.
print("omid",one);
print("omid",two);
?>

in this example $num consist of constant variable:"one,two, three" Now, how to implement it? is there Enum in php?

thanks your time

Community
  • 1
  • 1
Omid Nazifi
  • 5,235
  • 8
  • 30
  • 56

5 Answers5

5

There is no enum in php. Just define your constants beforehand and then use them. If you don't want to define them as global constants (and you probably should not in this case), you can define them inside your class.

class myclass {
    const ONE = 1;
    const TWO = 2;
    const THREE = 3;

    public function testit() {

        echo("omid". self::ONE);
        echo ("omid". self::TWO);
    }

}

If constant you are trying to use was not defined then you will get an error

Dmitri Snytkine
  • 1,096
  • 1
  • 8
  • 14
2

Are you looking for define()?

define('one',1);

This answer also has a good PHP solution for enums:

class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

var $today = DaysOfWeek::Sunday;
Community
  • 1
  • 1
Benjie
  • 7,701
  • 5
  • 29
  • 44
1

Is this what you want to do?

$nums = array(1 => 'one', 2 => 'two', 'three');
echo $nums[1]; // one
echo $nums[3]; // three
Fy-
  • 353
  • 1
  • 8
1

There are no enums, what you could do is this if you need this only for one function:

function foobar($str, $num){
  // allowed values (whitelist)
  static $num_allowed = array('one', 'two', 'three');
  if(!in_array($num, $num_allowed)){
    // error
  }
  // ...
}
middus
  • 9,103
  • 1
  • 31
  • 33
1

I am assuming you are wanting enumerated types:

Try some code like this

class DAYS
{
   private $value;
   private function __construct($value)
   {
      $this->value = $value;
   }
   private function __clone()
   {
      //Empty
   }
   public static function MON() { return new DAYS(1); }
   public static function TUE() { return new DAYS(2); }
   public static function WED() { return new DAYS(3); }
   public function AsInt() { return $this->value; }
}

I have a web page that you can use to generate this code: http://well-spun.co.ukcode_templates/enums.php

Ed Heal
  • 59,252
  • 17
  • 87
  • 127