Is there a datatype in javaScript or PHP etc. that can contain just a view different custom values.
Like a boolean but with three types.
Like something like this:
the value must be one of the following things "above", "under" or "in the middle".
Is there a datatype in javaScript or PHP etc. that can contain just a view different custom values.
Like a boolean but with three types.
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
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:
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 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/
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
}