简体   繁体   English

是否存在具有不同值的数据类型,例如 boolean

[英]is there a datatype with thee different values like a boolean

Is there a datatype in javaScript or PHP etc. that can contain just a view different custom values. javaScript 或 PHP 等中是否有一个数据类型可以只包含一个视图不同的自定义值。 Like a boolean but with three types.与 boolean 类似,但具有三种类型。 Like something like this:像这样:
the value must be one of the following things "above", "under" or "in the middle".该值必须是以下“上方”、“下方”或“中间”之一。

Hey in JavaScript there is no such thing, but you can use number and create some kind of enum like this嘿,在 JavaScript 中没有这样的东西,但你可以使用数字并创建某种像这样的枚举

const ENUM = {
  ABOVE: 1,
  MIDDLE: 0,
  UNDER: -1
}

and then use it like this:然后像这样使用它:


function acceptValue(en) {
  if (en === ENUM.ABOVE) {
    /* do something */
  }
}

Not in PHP, but you could build your custom types like this:不在 PHP 中,但您可以像这样构建您的自定义类型:

class catLocation
{
    protected $val;
    protected $allowed = ['on', 'under'];

    public function __construct(string $val)
    {
        if(!in_array($val, $this->allowed)) {
            throw new InvalidArgumentException('catLocation must be on or under');
        }
        $this->val = $val;
    }

    public function __invoke()
    {
         return $this->val;   
    }
}

... typehint it in your function definitions: ...在您的 function 定义中输入提示:

function whereIsCat(catLocation $loc) {
    return 'The cat is ' . $loc() . ' the table.'; 
    // Calling your object like a function will call the "magic" __invoke() method
}

... and use it like that: ...并像这样使用它:

$kitty_loc = new catLocation('under');

echo whereIsCat($kitty_loc); // The cat is under the table.

solution from this website: https://www.sohamkamani.com/blog/2017/08/21/enums-in-javascript/该网站的解决方案: https://www.sohamkamani.com/blog/2017/08/21/enums-in-javascript/

const seasons = {
  SUMMER: {
    BEGINNING: "summer.beginning",
    ENDING: "summer.ending"
  },
  WINTER: "winter",
  SPRING: "spring",
  AUTUMN: "autumn"
};

let season = seasons.SUMMER.BEGINNING;

if (!season) {
  throw new Error("Season is not defined");
}

switch (season) {
  case seasons.SUMMER.BEGINNING:
  // Do something for summer beginning
  case seasons.SUMMER.ENDING:
  // Do something for summer ending
  case seasons.SUMMER:
  // This will work if season = seasons.SUMMER
  // Do something for summer (generic)
  case seasons.WINTER:
  //Do something for winter
  case seasons.SPRING:
  //Do something for spring
  case seasons.AUTUMN:
  //Do something for autumn
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM