How to document available options for string parameter
Asked Answered
U

2

7

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;
}
Unexceptional answered 25/6, 2011 at 9:9 Comment(0)
D
7

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 :)

Durga answered 25/6, 2011 at 9:18 Comment(1)
Thanks a lot, and really like the use of constants to provide a more descriptive and easily memorable solutionUnexceptional
S
1

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);

Demo

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());

Demo

Shady answered 11/10, 2024 at 9:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.