Reputation: 4604
I have a public method for a class and I would like to document the available string values that the method can accept. Would this be acceptable:
/**
* Set size of photos
*
* @param string $size can be one of these options: url_sq, url_t, url_s, url_m, url_o
* @return void
*/
public function setSize($size){
$this->_size = $size;
}
Upvotes: 7
Views: 2664
Reputation: 146450
Starting on PHP/8.1 you can use a string backed enumeration:
<?php
enum Size: string
{
case url_sq = 'url_sq';
case url_t = 'url_t';
case url_s = 'url_s';
case url_m = 'url_m';
case url_o = 'url_o';
}
class Example
{
private string $_size;
/**
* Set size of photos.
*/
public function setSize(Size $size): void
{
$this->_size = $size->value;
}
}
$foo = new Example();
$foo->setSize(Size::url_t);
var_dump($foo);
Note that enums are like little classes, so the string value doesn't need to match the enum name, and you can add custom methods as well.
In many situations, you don't really need the string itself, just having a way to tell out which case was passed. That can make things simpler:
enum Size
{
case url_sq;
case url_t;
case url_s;
case url_m;
case url_o;
}
class Example
{
private Size $_size;
/**
* Set size of photos.
*/
public function setSize(Size $size): void
{
$this->_size = $size;
}
public function isSizeT(): bool
{
return $this->_size === Size::url_t;
}
}
$foo = new Example();
$foo->setSize(Size::url_t);
var_dump($foo->isSizeT());
$foo->setSize(Size::url_sq);
var_dump($foo->isSizeT());
Upvotes: 1
Reputation:
Yes, it's acceptable, but you can do it smarter:
class TheClass
{
const PHOTO_SIZE_SQ = 'url_sq';
const PHOTO_SIZE_TINY = 'url_t';
const PHOTO_SIZE_SMALL = 'url_s';
const PHOTO_SIZE_M = 'url_m';
const PHOTO_SIZE_O = 'url_o';
/**
* Set size of photos
*
* @param string $size see photo_size_* constants
* @return void
*/
public function setSize($size){
$this->_size = $size;
}
}
So when you will call this function, you can use IDE's autocompletion, to not keep in memory all values and to be sure that your code typed correct, without typos:
$object->setSize($object::PHOTO_SIZE_SMALL);
Of course, names of constants can be more short and more descriptive, when you are author of the code :)
Upvotes: 7