Php var name to string

Convert PHP Arrays, Integers, Objects & Variables to String

Today we are going to learn how to convert arrays, integers, objects, and variables to string in PHP. We will learn to use various built-in php functions or methods to deal with string conversion.

Table of Contents

Convert PHP Variable to String

I could convert a variable to string in PHP with my eyes shut. Jokes apart, PHP provides lots of pre-built function to deal with string conversion, we are going to use __toString() method to convert variable to string. Let us check out the below example:

 class convertToString public $str; public function __construct($str)  $this->str = $str; > public function __toString()  return (string) $this->str; > > $myObj = new convertToString('Days Gone'); echo $myObj; ?> // Result: Days Gone 

In the above example, we have used the __toString() function to convert variable to string. This function doesn’t take any argument, and it is mostly used with Objects.

Convert String to Integer in PHP

Converting string to integer or numbers is extremely simple in PHP. PHP programming language supports the type conversion, and it offers numerous functions to convert a string into numbers.

Let us have a look on some the string to number conversion php functions with an example below.

The number_format() function in PHP is used to convert a string into an integer.

 $int = "109.126"; echo number_format($int), "\n"; echo number_format($int, 2); ?> // Result: 109 // Result: 109.13

In the next step, we’ll take help of primitive types to convert a string into an integer, double or float.

 $number = "30061987.0915"; // int echo (int)$number, "\n"; // double echo (double)$number, "\n"; // float echo (float)$number, "\n"; ?> // Result: 30061987 // Result: 30061987.0915 // Result: 30061987.0915

Convert PHP Array to String

We are using PHP’s implode function to convert array to a string. The implode function in php takes two parameters. In the first parameter, we pass the separator. This separator is used to separate the arrays, and however, if you don’t pass any argument, then it’ll return an empty separator. In the second parameter, we pass the array object, an array which needs to be converted into a string.

 $arrray = ['star wars', 'avengers', 'the matrix', 'ghost rider']; echo implode(' | ', $arrray); ?> // star wars | avengers | the matrix | ghost rider

Convert PHP String to Arrays

Converting a string into arrays in PHP is pretty straightforward. PHP offers various methods to convert string to arrays. We will have a look at explode and str_split built-in php functions. These methods split a string and convert it into arrays, let us check out the examples below:

Using PHP’s Explode Function
Let us begin with the PHP’s explode() function, this method takes 2 argument to convert string into array. The 1st argument takes the delimiter to explode the function, and the 2nd argument takes a string. To know more about php you can visit their official site here.

 $string = 'The Fountainhead, Dumbo, The Man Who Laughs, 7 Faces of Dr. Lao, Moulin Rouge'; $movies_arr = explode(', ', $string); var_dump($movies_arr); ?> /* Result: array(5) < [0]=>string(16) "The Fountainhead" [1]=> string(5) "Dumbo" [2]=> string(18) "The Man Who Laughs" [3]=> string(18) "7 Faces of Dr. Lao" [4]=> string(12) "Moulin Rouge" > */

Using PHP’s str_split Function to Convert String to Array
The str_split method also allows us to convert string to an array. The str_split function takes 2 arguments; in the first argument, we pass the string. In the second argument, we pass the number, and this number refers to an array element’s character length. By default, it is set to 1.

 $string = 'Loremipsumdolorsitamet'; $string_split = str_split($string, 3); var_dump($string_split); ?> /* Result: array(8) < [0]=>string(3) "Lor" [1]=> string(3) "emi" [2]=> string(3) "psu" [3]=> string(3) "mdo" [4]=> string(3) "lor" [5]=> string(3) "sit" [6]=> string(3) "ame" [7]=> string(1) "t" > */

Convert PHP Integer to a String

Converting Integer to a string in php is not that difficult, we can use PHP’s built-in strval() function. This function is fully capable of converting string, Integer and double to a string. The important thing is to remember about this function is it shouldn’t be used with objects and arrays; if used, then this will return the type name.

The Strval Function Syntax

This function takes one parameter, and that is the numerical value which needs to be converted to string. This function returns the string value as you can see in the below example.

 $var = 124.061; echo strval($var); ?> // Result: 124.061

Convert String to Date/DateTime

The php offers some useful built-in functions to convert string to Date and DateTime. In this example, I’ll show you how to use strtotime(), and getDate() functions to achieve the desired results:

String to Date and DateTime Conversion using Strtotime() Example:

The strtotime() Syntax
The strtotime() in php function takes Time/Date and now (optional) parameter and returns the numerical value in seconds since Jan 1, 1970.

The getDate() Syntax
The getDate() is useful for retrieving date/time information based on the date and time values passed into the function:

 $time_var = strtotime("2017/02/30"); $date_var = getDate($time_var); print_r ($date_var); ?> /* Result: Array( [seconds] => 0 [minutes] => 0 [hours] => 0 [mday] => 2 [wday] => 4 [mon] => 3 [year] => 2017 [yday] => 60 [weekday] => Thursday [month] => March [0] => 1488412800 ) */

Convert PHP Object to String

Now, we will covert a php object into the string using the following approach. We are taking help of __toString() and serialize() function help for converting object to string in php. We’ve already discused toString() function in the above example, let us understand what serialize() function is in php.

The serialize() method returns a string containing a byte-stream representation of any value that can be stored in PHP.
Reference: https://www.php.net/manual/en/language.oop5.serialization.php

 class NewObject  public $name = 'John Wick'; public function __toString()  return "Movie name is: $this->name>\n"; > > $OBJECT = new NewObject; echo $OBJECT; echo serialize($OBJECT); ?> /* Result: Movie name is: John Wick O:9:"NewObject":1: */ 

Conclusion

In this PHP tutorial, we have learnt how to deal with strings conversion, whether it is arrays, integer, objects, or variables. I hope this tutorial will help you if you liked this tutorial, then don’t forget to share it with others. Thanks for reading, and have a good day!

positronX.io - Tamso Ma Jyotirgamaya

A Full-stack developer with a passion to solve real world problems through functional programming.

Источник

Как получить имя переменной в виде строки в PHP?

Вы можете использовать get_defined_vars(), чтобы найти имя переменной, которая имеет то же значение, что и то, которое вы пытаетесь найти Имя. Очевидно, что это не всегда будет работать, поскольку разные переменные часто имеют одинаковые значения, но это единственный способ, которым я могу это сделать. Изменить: get_defined_vars() работает некорректно, он возвращает ‘var’, потому что $$ используется в самой функции. $GLOBALS, похоже, работает, поэтому я изменил его на это.

function print_var_name($var) < foreach($GLOBALS as $var_name =>$value) < if ($value === $var) < return $var_name; >> return false; > 

Изменить: чтобы быть ясным, в PHP нет хорошего способа сделать это, вероятно, потому, что вам не нужно это делать. Вероятно, есть лучшие способы сделать то, что вы пытаетесь сделать.

Я тоже не мог придумать способ сделать это эффективно, но я придумал это. Он работает для ограниченного использования ниже. развести руками

 $foo = "knight"; $bar = array( 1, 2, 3 ); $baz = 12345; varName( $foo ); varName( $bar ); varName( $baz ); ?> // Returns Array ( [0] => $foo [1] => foo ) Array ( [0] => $bar [1] => bar ) Array ( [0] => $baz [1] => baz ) 

Он работает на основе строки, которая называется функцией, где находит аргумент, который вы передали. Я полагаю, его можно было бы расширить, чтобы работать с несколькими аргументами, но, как говорили другие, если бы вы могли лучше объяснить ситуацию, решение, вероятно, будет работать лучше.

$var_name = "FooBar"; $$var_name = "a string"; 
  • «Переменная» — это просто символ, указывающий на что-то другое. В PHP он внутренне указывает на то, что называется «zval», которое фактически может использоваться для нескольких переменных одновременно, либо потому, что они имеют одинаковое значение (PHP реализует нечто, называемое «copy-on-write», так что $foo = $bar doesn ‘ t необходимо выделить дополнительную память сразу) или потому, что они были назначены (или переданы функции) по ссылке (например, $foo =& $bar ). Таким образом, zval не имеет имени.
  • Когда вы передаете параметр функции, вы создаете новую переменную (даже если это ссылка). Вы можете передать что-то анонимное, например «hello» , но один раз внутри вашей функции, какую бы переменную вы ни назвали. Это довольно фундаментально для разделения кода: если функция полагалась на то, что была вызвана переменной, это было бы скорее как goto , чем правильно отдельная функция.
  • Глобальные переменные обычно считаются плохими. Многие примеры здесь предполагают, что переменную, которую вы хотите «отразить», можно найти в $GLOBALS , но это будет верно, только если вы плохо структурировали свой код, а переменные не привязаны к какой-либо функции или объекту.
  • Переменные имена есть, чтобы помочь программистам прочитать их код. Переименование переменных, чтобы лучше соответствовать их назначению, является очень распространенной практикой рефакторинга, и все дело в том, что это не имеет никакого значения.

Теперь я понимаю стремление к этому для отладки (хотя некоторые из предложенных применений выходят далеко за рамки этого), но в качестве обобщенного решения это на самом деле не так полезно, как вы могли подумать: если ваша функция отладки говорит, что ваша переменная называется «$ file» , который все равно может быть любой из десятков переменных «$ file» в вашем коде или переменной, которую вы назвали «$ filename», но передаете функцию, параметр которой называется «$ file» .

Более полезная часть информации — это то, где в коде вызывается функция отладки. Поскольку вы можете быстро найти это в своем редакторе, вы можете увидеть, какую переменную вы выводили для себя, и можете даже передать в нее целые выражения за один раз (например, debug(‘$foo + $bar = ‘ . ($foo + $bar)) ).

Для этого вы можете использовать этот фрагмент в верхней части своей функции отладки:

$backtrace = debug_backtrace(); echo '# Debug function called from ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line']; 

Я сделал функцию проверки для отладки. Это похоже на print_r() на стероиды, подобно Krumo, но немного эффективнее на объектах. Я хотел добавить определение имени var и вышел с этим, вдохновленный сообщением Ника Престы на этой странице. Он обнаруживает любое выражение, переданное как аргумент, а не только имена переменных.

Это только функция-обертка, которая обнаруживает переданное выражение. Работает в большинстве случаев. Он не будет работать, если вы вызовете функцию более одного раза в одной строке кода.

Это прекрасно работает: умереть (инспектировать ( $this- > GetUser() → hasCredential ( «Удалить» ) ));

inspect() — это функция, которая будет обнаруживать переданное выражение.

Мы получаем: $this- > getUser() → hasCredential ( «delete» )

function inspect($label, $value = "__undefin_e_d__") < if($value == "__undefin_e_d__") < /* The first argument is not the label but the variable to inspect itself, so we need a label. Let try to find out it name by peeking at the source code. */ /* The reason for using an exotic string like "__undefin_e_d__" instead of NULL here is that inspected variables can also be NULL and I want to inspect them anyway. */ $value = $label; $bt = debug_backtrace(); $src = file($bt[0]["file"]); $line = $src[ $bt[0]['line'] - 1 ]; // let match the function call and the last closing bracket preg_match( "#inspect\((.+)\)#", $line, $match ); /* let count brackets to see how many of them actually belongs to the var name Eg: die(inspect($this->getUser()->hasCredential("delete"))); We want: $this->getUser()->hasCredential("delete") */ $max = strlen($match[1]); $varname = ""; $c = 0; for($i = 0; $i < $max; $i++)< if( $match[1]== "(" ) $c++; elseif( $match[1] == ")" ) $c--; if($c < 0) break; $varname .= $match[1]; > $label = $varname; > // $label now holds the name of the passed variable ($ included) // Eg: inspect($hello) // => $label = "$hello" // or the whole expression evaluated // Eg: inspect($this->getUser()->hasCredential("delete")) // => $label = "$this->getUser()->hasCredential(\"delete\")" // now the actual function call to the inspector method, // passing the var name as the label: // return dInspect::dump($label, $val); // UPDATE: I commented this line because people got confused about // the dInspect class, wich has nothing to do with the issue here. echo("The label is: ".$label); echo("The value is: ".$value); > 

Здесь приведен пример функции инспектора (и моего класса dInspect):

Тексты находятся на испанском языке на этой странице, но код является кратким и очень легким для понимания.

Источник

Читайте также:  Статьи комментарии php mysql
Оцените статью