Found 1046 Articles for PHP

PHP Generators.

Malhar Lathkar
Updated on 18-Sep-2020 09:15:49

2K+ Views

IntroductionTraversing a big collection of data using looping construct such as foreach would require large memory and considerable processing time. With generators it is possible to iterate over a set of data without these overheads. A generator function is similar to a normal function. However, instead of return statement in a function, generator uses yield keyword to be executed repeatedly so that it provides values to be iterated.The yield keyword is the heart of generator mechanism. Even though its use appears to be similar to return, it doesn't stop execution of function. It provides next value for iteration and pauses ... Read More

PHP Generators vs Iterator objects

Malhar Lathkar
Updated on 18-Sep-2020 09:12:48

432 Views

IntroductionWhen a generator function is called, internally, a new object of Generator class is returned. It implements the Iterator interface. The iterator interface defines following abstract methodsIterator::current — Return the current elementIterator::key — Return the key of the current elementIterator::next — Move forward to next elementIterator::rewind — Rewind the Iterator to the first elementIterator::valid — Checks if current position is validGenerator acts as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.Generator as interatorIn following example, generator functions yields lines in a file ... Read More

PHP Throwing Exceptions

Malhar Lathkar
Updated on 18-Sep-2020 09:10:58

260 Views

IntroductionThrowable interface is implemented by Error and Exception class. All predefined Error classes are inherited from Error class. Instance of corresponding Error class is thrown inside try block and processed inside appropriate catch block.Throwing ErrorNormal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence.Example Live DemoOutputFollowing output is displayed2 Caught exception: Division by zero. Execution continuesIn following example, TypeError is thrown while executing a function because appropriate arguments are not passed to it. Corresponding error message is displayedExample Live DemoOutputFollowing output is displayedArgument 2 passed to add() must be of the ... Read More

PHP Nested Exception

Malhar Lathkar
Updated on 18-Sep-2020 09:04:43

474 Views

IntroductionBlocks of try - catch can be nested upto any desired levels. Exceptions will be handled in reverse order of appearance i.e. innermost exception processing is done first.ExampleIn following example,inner try block checks if either of two varibles are non-numeric, nd if so, throws a user defined exception. Outer try block throws DivisionByZeroError if denominator is 0. Otherwise division of two numbers is displayed.Example Live DemoOutputFollowing output is displayedDivision by 0 in line no 19Change any one of varibles to non-numeric valueerror : Non numeric data in line no 20If both variables are numbers, their division is printed

PHP Exception Handling with Multiple catch blocks

Malhar Lathkar
Updated on 18-Sep-2020 09:00:52

1K+ Views

IntroductionPHP allows a series of catch blocks following a try block to handle different exception cases. Various catch blocks may be employed to handle predefined exceptions and errors as well as user defined exceptions.ExampleFollowing example uses catch blocks to process DivisioByZeroError, TypeError, ArgumentCountError and InvalidArgumentException conditions. There is also a catch block to handle general Exception.Example Live DemoOutputTo begin with, since denominator is 0, Divide by 0 error will be displayedDivision by 0Set $b=3 which will cause TypeError because divide function is expected to return integer but dividion results in floatReturn value of divide() must be of the type integer, float ... Read More

PHP Errors in PHP7

Malhar Lathkar
Updated on 18-Sep-2020 08:57:16

274 Views

IntroductionPrior to version 7, PHP parser used to report errors in response to various conditions. Each error used to be of a certain predefined type. PHP7 has changed the mechanism of error reporting. Instead of traditional error reporting, most errors are now reported by throwing error exceptions.If error exceptions go unhandled, a fatal error is reported and will be handled like traditional error condition. PHP's error heirarchy starts from Throwable interface. All predefined errors such as ArithmeticError, AssertionError, CompileError and TypeError are classes implementing Throwable iterface. Exception in PHP 7 is also implements Throwable interface.Throwable interface acts as base for ... Read More

PHP Interaction between finally and return

Malhar Lathkar
Updated on 18-Sep-2020 08:47:10

1K+ Views

IntroductionThere is a peculiar behaviour of finally block when either try block or catch block (or both) contain a return statement. Normally return statement causes control of program go back to calling position. However, in case of a function with try /catch block with return, statements in finally block are executed first before returning.ExampleIn following example, div() function has a try - catch - finally construct. The try block without exception returns result of division. In case of exception, catch block returns error message. However, in either case statement in finally block is executed first.Example Live DemoOutputFollowing output is displayedThis block ... Read More

PHP Exception Handling with finally

Malhar Lathkar
Updated on 18-Sep-2020 08:45:23

378 Views

IntroductionCode in finally block will always get executed whether there is an exception in ry block or not. This block appears either after catch block or instead of catch block.catch and finally blockIn following example, both catch and finally blocks are given. If execption occurs in try block, code in both is executed. If there is no exception, only finally block is executed.Example Live DemoOutputFollowing output is displayedCaught exception: Division by zero. This block is always executed Execution continueschange statement in try block so that no exception occursExample Live DemoOutputFollowing output is displayed2 This block is always executed Execution continuesfinally block onlyFollowing ... Read More

PHP Extending Exceptions

Malhar Lathkar
Updated on 18-Sep-2020 08:42:05

711 Views

IntroductionException class implements Throwable interface and is base class for all Exception classes, predefined exceptions as well as user defined exceptions. The Exception class defines some final (non-overridable) methods to implement those from Throwable interface, and __tostring() method that can be overridden to return a string representation of Exception object.final public function getMessage()message of exceptionfinal public function getCode()code of exceptionfinal public function getFile()source filenamefinal public function getLine()source linefinal public function getTrace()an array of the backtrace()final public function getPrevious()previous exceptionfinal public function getTraceAsString()formatted string of tracepublic function __toString()formatted string for displayIf user defined exception class re-defines the constructor, it should call parent::__construct() to ensure ... Read More

PHP declare Statement

Malhar Lathkar
Updated on 18-Sep-2020 12:52:13

490 Views

IntroductionSyntax of declare statement in PHP is similar to other flow control structures such as while, for, foreach etc.Syntaxdeclare (directive) {    statement1;    statement2;    . . }Behaviour of the block is defined by type of directive. Three types of directives can be provided in declare statement - ticks, encoding and strict_types directive.ticks directiveA tick is a name given to special event that occurs a certain number of statements in the script are executed. These statements are internal to PHP and roughky equal to the statements in your script (excluding conditional and argument expressions. Any function can be associated ... Read More

Advertisements