简体   繁体   中英

check if item can be converted to string?

I am writing a debug method.

What I have is

if(is_xxx($item)){
 //echo output info for type
}

what I want to do at the end is

if(can_be_string($item))
echo $item;

Is there a can_be_string type function?

Ok, edited, with incorporating Michiel Pater 's suggestion (who's answer is gone now) ans @eisberg's suggestions. settype will return true with objects no matter what, as it seems.

if(
    ( !is_array( $item ) ) &&
    ( ( !is_object( $item ) && settype( $item, 'string' ) !== false ) ||
    ( is_object( $item ) && method_exists( $item, '__toString' ) ) )
)
{
    echo $item;
}

For the sake of completion...

http://www.php.net/is_scalar , available since PHP 4; not a single word about it.. :)

How about

function can_be_string($var) {
    return $var === null || is_scalar($var) || (is_object($var) && method_exists($var, '__toString'));
}

And since PHP 8 you can replace the third condition with $var instanceof Stringable

Quick and dirty implementation with test:

function canBeString($value)
{
    if (is_object($value) and method_exists($value, '__toString')) return true;

    if (is_null($value)) return true;

    return is_scalar($value);
}

class MyClass
{    
}

$object = new MyClass();
var_dump(canBeString($object)); // bool(false)

class MyClassWithToString
{
    public function __toString()
    {
        return 'foo';
    }
}

$objectWithToString = new MyClassWithToString();
var_dump(canBeString($objectWithToString)); // bool(true)

var_dump(canBeString(1)); // bool(true)
echo (string)1 . "\n";

var_dump(canBeString(false)); // bool(true)
echo (string)true . "\n";

var_dump(canBeString(1.0)); // bool(true)
echo (string)1.0 . "\n";

var_dump(canBeString(null)); // bool(false)
var_dump((string)null); // string(0) ""

Here is the shortest way I can find:

/**
 * Determine if we can cast a value to a string.
 *
 * @param mixed $v
 *
 * @return bool
 */
function can_be_string($v): bool
{
    return method_exists($v, '__toString') || $v === null || is_scalar($v);
}

how about this decision?

function canBeString ($value) {
    try {
        $value = (string) $value;
    } catch (\ErrorException $exception) {
        return false;
    }

    return true;
}

If is_string() doesn't help you, then I can only suggest some ideas:

  • Trap strlen() or indeed another function that throws an error if the variable is not a string
  • if not NULL, use to_string() and check if the string contains only numeric characters. If not (and the variable/object is a simple variable) you could assume something

It's very simple:

function can_be_string($var)
{
    return method_exists($var, '__toString') || (is_scalar($var) && !is_null($var));
}

The code has already been tested. The method_exists() function returns false if $var is not an object, so this verification is not necessary.

I didn't think any of the answers were satisfactory.

Simplest implementation:

function can_be_string($value) {
    return (!is_object($value) && !is_array($value))
        || method_exists($value, '__toString');
}

class IsString {
    public function __toString() {
        return 'hello';
    }
}

var_dump(
    can_be_string(null), // true
    can_be_string(123), // true
    can_be_string(12.3), // true
    can_be_string('hello'), // true
    can_be_string(new IsString), // true
    can_be_string(new stdClass), // false
    can_be_string([1, 2, 3]) // false
);

With print_r() and var_dump() functions you can print-out contents of any variable.

In case you don't like the output of mentioned functions, there is a plenty of type checking functions here http://www.php.net/manual/en/ref.var.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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