Error
Error is the base class for all internal PHP errors.
Class synopsis
Properties
The filename where the error happened
The line where the error happened
The previously thrown exception
The string representation of the stack trace
The stack trace as an array
Table of Contents
- Error::__construct — Construct the error object
- Error::getMessage — Gets the error message
- Error::getPrevious — Returns previous Throwable
- Error::getCode — Gets the error code
- Error::getFile — Gets the file in which the error occurred
- Error::getLine — Gets the line in which the error occurred
- Error::getTrace — Gets the stack trace
- Error::getTraceAsString — Gets the stack trace as a string
- Error::__toString — String representation of the error
- Error::__clone — Clone the error
User Contributed Notes 3 notes
Lists of Throwable and Exception tree as of 7.2.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
ParseError
TypeError
ArgumentCountError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Lists of Throwable and Exception tree as of 8.1.0
Error
ArithmeticError
DivisionByZeroError
AssertionError
CompileError
ParseError
FiberError
TypeError
ArgumentCountError
UnhandledMatchError
ValueError
Exception
ClosedGeneratorException
DOMException
ErrorException
IntlException
JsonException
LogicException
BadFunctionCallException
BadMethodCallException
DomainException
InvalidArgumentException
LengthException
OutOfRangeException
PharException
ReflectionException
RuntimeException
OutOfBoundsException
OverflowException
PDOException
RangeException
UnderflowException
UnexpectedValueException
SodiumException
Initially posted by whysteepy at gmail dot com for PHP 7.2.0, based on the gist
If after PHP upgrade you’re getting error «PHP Fatal error: Cannot declare class error, because the name is already in use . «, you will have to rename your «error» class.
Since PHP 7 classname «Error» is predefined and used internally.
- Predefined Exceptions
- Exception
- ErrorException
- Error
- ArgumentCountError
- ArithmeticError
- AssertionError
- DivisionByZeroError
- CompileError
- ParseError
- TypeError
- ValueError
- UnhandledMatchError
- FiberError
Laravel validation Error messages to string
I want to convert laravel validation error array to a comma separated string. This is to use in an api service for an ios application. So that the iOs developer can process error messages easily. I tried,
$valArr = []; foreach ($validator->errors() as $key => $value) < $errStr = $key.' '.$value[0]; array_push($valArr, $errStr); >if(!empty($valArr))
4 Answers 4
$errorString = implode(",",$validator->messages()->all());
$validator = Validator::make($dataToBeChecked,$validationArray,$messageArray)
You are not converting validation errors to array.Please use the below function and pass validation errors as parameter. public function validationErrorsToString($errArray) < $valArr = array(); foreach ($errArray->toArray() as $key => $value) < $errStr = $key.' '.$value[0]; array_push($valArr, $errStr); >if(!empty($valArr)) < $errStrFinal = implode(',', $valArr); >return $errStrFinal; > //Function call. $result = $this->validationErrorsToString($validator->errors());
The $validator->errors() returns a MessageBag ,
You are close, you need to call the getMessages() function on errors() , so:
foreach ($validator->errors()->getMessages() as $key => $value)
If you are doing it like me without your validator and you are pulling messages from the exception you can use laravel helper Arr::flatten($array);
Link and code are for laravel 8.x but I tested this with 5.7 😉 It works.
use Illuminate\Support\Arr; $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]; $flattened = Arr::flatten($array); // ['Joe', 'PHP', 'Ruby']
try < $request->validate([ 'test1' => 'required|integer', 'test2' => 'required|integer', 'test3' => 'required|string', ]); > catch (ValidationException $validationException) < return response()->json([ 'type' => 'error', 'title' => $validationException->getMessage(), 'messages' => Arr::flatten($validationException->errors()) ], $validationException->status); > catch (\Exception $exception) < return response()->json([ 'type' => 'error', 'title' => $exception->getMessage(), ], $exception->getCode()); >
As you can see I am pulling the message and setting it as my title. Then I am using Arr::flatten($validationException->errors()) to get the validation messages and but to flatten my array for SweetAlert2 on the frontend.
I know I am late but I hope it will help someone that comes across these problems.
PHP 7 strict type object to string conversion
Now when I feed this function an object, I expect a Type Error to be thrown. But this is not the case, an object of type SimpleXmlElement is silently converted to a string: https://3v4l.org/lQdaZ Is this a bug or a feature?
3 Answers 3
As the documentation of the magic function __toString() explains:
The __toString() method allows a class to decide how it will react when it is treated like a string.
Because the class SimpleXmlElement implements the __toString() magic method, it (the method) is invoked every time a SimpleXmlElement is used where a string is expected. The value returned by __toString() is used instead of the object.
It is difficult to tell if this is a feature or a bug 1 . The function testXml() currently expects a string as argument and you are not pleased by the fact that it silently accepts a SimpleXmlElement instead.
If you remove the type of its argument, the call to __toString() does not happen any more and the value of the $xml argument inside the function is the SimpleXmlElement object. The call to __toString() happens in the echo "this is a string: " .$xml; line and it's very convenient that you can print the value of $xml even if it is not a string.
If you think it is a bug then echo (which expects strings as arguments) should complain about the type of $xml and should not print it. Not that convenient, isn't it?
1 It is not a bug, this is how the language evolved. __toString() was introduced before type declarations for scalar types and, in order to not break the existing behaviour, it is invoked if it's possible instead of triggering an error about incorrect type of the argument.
check if item can be converted to string?
@Hailwood the only items I know that cannot become string are objects without __toString() method. Where do you get into problems?
What is the determinant of whether something can be a string or not? I don't understand the question.
I don't believe that a Resource can be cast to string either - not just objects (unless they have __toString) but I think those are the only exceptions
yeah, this function has no control over what is plugged into it. so someone could pass in for example a database resource, which could not be converted to a string.
Add a trap for is_null() as well if you're echoing rather than var_dumping. else you won't see what's echoed
10 Answers 10
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' ) ) ) )
Integers, double, float, . can be casted as well. Arrays too, but without giving any useful information 🙂
I would say if I really need to debug anything by hand an not by var_dump() , var_export() , print_r() , . I would switch / case the gettype() .
For the sake of completion.
http://www.php.net/is_scalar, available since PHP 4; not a single word about it.. 🙂
Some objects can be cast to string. That is if they implement magical method __toString() . Also the note says it doesn't consider null value scalar for some reason. On top of that using this function on resources seems unreliable.
function can_be_string($var)
And since PHP 8 you can replace the third condition with $var instanceof Stringable
This will return the incorrect result if passed an object with a permissive __call function, see: 3v4l.org/4ttLv. Use method_exists instead of is_callable
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) ""