Var to str php

strval

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format() .

Parameters

The variable that is being converted to a string .

value may be any scalar type, null , or an object that implements the __toString() method. You cannot use strval() on arrays or on objects that do not implement the __toString() method.

Return Values

The string value of value .

Examples

Example #1 strval() example using PHP magic __toString() method.

class StrValTest
public function __toString ()
return __CLASS__ ;
>
>

// Prints ‘StrValTest’
echo strval (new StrValTest );
?>

See Also

  • boolval() — Get the boolean value of a variable
  • floatval() — Get float value of a variable
  • intval() — Get the integer value of a variable
  • settype() — Set the type of a variable
  • sprintf() — Return a formatted string
  • number_format() — Format a number with grouped thousands
  • Type juggling
  • __toString()

User Contributed Notes 9 notes

As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.

Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: «Object»
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error: Object of class X could not be converted to string

If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here’s a function to do it.

Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.

The function returns ‘#’ if the argument does not represent a whole number.

$nwords = array( «zero» , «one» , «two» , «three» , «four» , «five» , «six» , «seven» ,
«eight» , «nine» , «ten» , «eleven» , «twelve» , «thirteen» ,
«fourteen» , «fifteen» , «sixteen» , «seventeen» , «eighteen» ,
«nineteen» , «twenty» , 30 => «thirty» , 40 => «forty» ,
50 => «fifty» , 60 => «sixty» , 70 => «seventy» , 80 => «eighty» ,
90 => «ninety» );

Читайте также:  Html какие шрифты можно использовать

function int_to_words ( $x ) global $nwords ;

if(! is_numeric ( $x ))
$w = ‘#’ ;
else if( fmod ( $x , 1 ) != 0 )
$w = ‘#’ ;
else if( $x < 0 ) $w = 'minus ' ;
$x = — $x ;
> else
$w = » ;
// . now $x is a non-negative integer.

if( $x < 21 ) // 0 to 20
$w .= $nwords [ $x ];
else if( $x < 100 ) < // 21 to 99
$w .= $nwords [ 10 * floor ( $x / 10 )];
$r = fmod ( $x , 10 );
if( $r > 0 )
$w .= ‘-‘ . $nwords [ $r ];
> else if( $x < 1000 ) < // 100 to 999
$w .= $nwords [ floor ( $x / 100 )] . ‘ hundred’ ;
$r = fmod ( $x , 100 );
if( $r > 0 )
$w .= ‘ and ‘ . int_to_words ( $r );
> else if( $x < 1000000 ) < // 1000 to 999999
$w .= int_to_words ( floor ( $x / 1000 )) . ‘ thousand’ ;
$r = fmod ( $x , 1000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$w .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
> else < // millions
$w .= int_to_words ( floor ( $x / 1000000 )) . ‘ million’ ;
$r = fmod ( $x , 1000000 );
if( $r > 0 ) $w .= ‘ ‘ ;
if( $r < 100 )
$word .= ‘and ‘ ;
$w .= int_to_words ( $r );
>
>
>
return $w ;
>

?>

Usage:
echo ‘There are currently ‘ . int_to_words ( $count ) . ‘ members logged on.’ ;
?>

I can’t help being surprised that

evaluates to true. It’s the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.

The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624

It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 — (-1968766020) = 4294967296.

As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

/**
* Returns the string value of a variable
*
* This differs from strval in that it invokes __toString if an object is given
* and the object has that method
*/
function stringVal ($value)
// We use get_class_methods instead of method_exists to ensure that __toString is a public method
if (is_object($value) && in_array(«__toString», get_class_methods($value)))
return strval($value->__toString());
else
return strval($value);
>

In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )

Читайте также:  Metanit java stream api

function int_to_words($x) global $nwords;

if(!is_numeric($x))
$w = ‘#’;
else if(fmod($x, 1) != 0)
$w = ‘#’;
else if($x < 0) $w = $nwords['minus'].' ';
$x = -$x;
> else
$w = »;
// . now $x is a non-negative integer.

if($x < 21) // 0 to 20
$w .= $nwords[$x];
else if($x < 100) < // 21 to 99
$w .= $nwords[10 * floor($x/10)];
$r = fmod($x, 10);
if($r > 0)
$w .= ‘-‘. $nwords[$r];
> else if($x < 1000) < // 100 to 999
$w .= $nwords[floor($x/100)] .’ ‘.$nwords[‘hundred’];
$r = fmod($x, 100);
if($r > 0)
$w .= ‘ ‘.$nwords[‘separator’].’ ‘. int_to_words($r);
> else if($x < 1000000) < // 1000 to 999999
$w .= int_to_words(floor($x/1000)) .’ ‘.$nwords[‘thousand’];
$r = fmod($x, 1000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$w .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);

>
> else < // millions
$w .= int_to_words(floor($x/1000000)) .’ ‘.$nwords[‘million’];
$r = fmod($x, 1000000);
if($r > 0) $w .= ‘ ‘;
if($r < 100)
$word .= $nwords[‘separator’].’ ‘;
$w .= int_to_words($r);
>
>
>
return $w;
>

// Usage in English
$nwords = array( «zero», «one», «two», «three», «four», «five», «six», «seven»,
«eight», «nine», «ten», «eleven», «twelve», «thirteen»,
«fourteen», «fifteen», «sixteen», «seventeen», «eighteen»,
«nineteen», «twenty», 30 => «thirty», 40 => «forty»,
50 => «fifty», 60 => «sixty», 70 => «seventy», 80 => «eighty»,
90 => «ninety» , «hundred» => «hundred», «thousand»=> «thousand», «million»=>»million»,
«separator»=>»and», «minus»=>»minus»);

echo ‘There are currently ‘. int_to_words(-120223456) . ‘ members logged on.
‘;

//Utilisation en Francais
$nwords = array( «zéro», «un», «deux», «trois», «quatre», «cinq», «six», «sept»,
«huit», «neuf», «dix», «onze», «douze», «treize»,
«quatorze», «quinze», «seize», «dix-sept», «dix-huit»,
«dix-neuf», «vingt», 30 => «trente», 40 => «quarante»,
50 => «cinquante», 60 => «soixante», 70 => «soixante-dix», 80 => «quatre-vingt»,
90 => «quatre-vingt-dix» , «hundred» => «cent», «thousand»=> «mille», «million»=>»million»,
«separator»=>»», «minus»=>»moins»);

echo ‘Il y a actuellement ‘. int_to_words(-120223456) . ‘ membres connectés.
‘;

Источник

strval

Возвращает строковое значение переменной. См. документацию по типу string для более подробной информации о преобразовании в строку.

Эта функция не производит форматирование возвращаемого значения. Если необходимо привести числовое значение к строке с особым форматом, воспользуйтесь sprintf() или number_format() .

Список параметров

Переменная, которую необходимо преобразовать в строку.

var может быть любого скалярного типа или объектом, который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().

Возвращаемые значения

Строковое значение ( string ) параметра var .

Примеры

Пример #1 Пример использования strval() с магическим методом PHP 5 __toString().

class StrValTest
public function __toString ()
return __CLASS__ ;
>
>

// Выводит ‘StrValTest’
echo strval (new StrValTest );
?>

Смотрите также

  • boolval() — Get the boolean value of a variable
  • floatval() — Возвращает значение переменной в виде числа с плавающей точкой
  • intval() — Возвращает целое значение переменной
  • settype() — Присваивает переменной новый тип
  • sprintf() — Возвращает отформатированную строку
  • number_format() — Форматирует число с разделением групп
  • Манипуляции с типами
  • __toString()
Читайте также:  Python googletrans attributeerror nonetype object has no attribute group

Источник

Манипуляции с типами

PHP не требует (и не поддерживает) явного типа при определении переменной; тип переменной определяется по контексту, в котором она используется. То есть, если вы присвоите значение типа string переменной $var , то $var станет строкой. Если вы затем присвоите $var целочисленное значение, она станет целым числом.

Примером автоматического преобразования типа является оператор сложения ‘+’. Если какой-либо из операндов является float , то все операнды интерпретируются как float , и результатом также будет float . В противном случае операнды будут интерпретироваться как целые числа и результат также будет целочисленным. Обратите внимание, что это НЕ меняет типы самих операндов; меняется только то, как они вычисляются и сам тип выражения.

$foo = «0» ; // $foo это строка (ASCII 48)
$foo += 2 ; // $foo теперь целое число (2)
$foo = $foo + 1.3 ; // $foo теперь число с плавающей точкой (3.3)
$foo = 5 + «10 Little Piggies» ; // $foo это целое число (15)
$foo = 5 + «10 Small Pigs» ; // $foo это целое число (15)
?>

Если последние два примера вам непонятны, смотрите Преобразование строк в числа.

Если вы хотите, чтобы переменная принудительно вычислялась как определенный тип, смотрите раздел приведение типов. Если вы хотите изменить тип переменной, смотрите settype() .

Если вы хотите протестировать любой из примеров, приведенных в данном разделе, вы можете использовать функцию var_dump() .

Замечание:

Поведение автоматического преобразования в массив в настоящий момент не определено.

К тому же, так как PHP поддерживает индексирование в строках аналогично смещениям элементов массивов, следующий пример будет верен для всех версий PHP:

Приведение типов

Приведение типов в PHP работает так же, как и в C: имя требуемого типа записывается в круглых скобках перед приводимой переменной.

Допускаются следующие приведения типов:

  • (int), (integer) — приведение к integer
  • (bool), (boolean) — приведение к boolean
  • (float), (double), (real) — приведение к float
  • (string) — приведение к string
  • (array) — приведение к array
  • (object) — приведение к object
  • (unset) — приведение к NULL (PHP 5)

Приведение типа (binary) и поддержка префикса b были добавлены в PHP 5.2.1

Обратите внимание, что внутри скобок допускаются пробелы и символы табуляции, поэтому следующие примеры равносильны по своему действию:

Приведение строковых литералов и переменных к бинарным строкам:

Замечание:

Вместо использования приведения переменной к string , можно также заключить ее в двойные кавычки.

$foo = 10 ; // $foo — это целое число
$str = » $foo » ; // $str — это строка
$fst = (string) $foo ; // $fst — это тоже строка

// Это напечатает «они одинаковы»
if ( $fst === $str ) echo «они одинаковы» ;
>
?>

Может быть не совсем ясно, что именно происходит при приведении между типами. Для дополнительной информации смотрите разделы:

Источник

Оцените статью