You are on page 1of 30

How can I control the width of a label tag?

R:
Label is an inline element, it cannot have width value; in order to do this you need to put display:block orfloat:left.

Using CSS, of course... label { display: block; width: 100px; } The width attribute is deprecated, and CSS should always be used to control these kinds of presentational styles. using the inline-block is better because it doesn't force the remaining elements and/or controls to be drawn in a new line .label { width:200px; display: inline-block; } Also you may set the position, for example to absolute, and width will be applied to label element

HOW TO STYLE CSS RADIO


Before and after: Our HTML code:

<ul> <li><label for="radio1">label 1</label> <span></span> <input type="radio" id="radio1" name="myRadio" checked="checked"/><span></span></li> <li><label for="radio2">label 2</label> <span></span><input type="radio" id="radio2" name="myRadio" /><span> </span></li> <li><label for="radio3">label 3</label><span></span> <input type="radio" id="radio3" name="myRadio" /><span></span></li> <li><label for="radio4">label 4</label><span></span> <input type="radio" id="radio4" name="myRadio" /><span></span></li> </ul>

We only have to add two empty span before and after the radio button. Here is the commented CSS code (only the essential to do the trick, without the eye-candy):
span{ position: absolute; right: 0; width: 25px; height: 25px; line-height: 25px; padding: 3px; color: #FFF; text-align: center; background: #c06f59; } span:after{ content: "no"; /*if CSS are disbled span elements are not displayed*/ } input{ position: absolute; right: 0; margin: 0; width: 31px; height: 31px; /*hide the radio button*/ filter:alpha(opacity=0); -moz-opacity:0; -khtml-opacity: 0; opacity: 0; cursor: pointer; } input[type="radio"] + span{ /*the span element that immediately follow the radio button */ visibility: hidden; /*temporarily hide the "YES" label*/ background: #6EB558; } input[type="radio"] + span:after{ content: "yes"; /*if CSS are disbled span elements are not displayed*/ }

input[type="radio"]:checked + span{ visibility: visible; /*show the "YES" label only if the radio button is checked*/ }

Horizontal lists - all steps combined


Make a basic list
Start with a basic unordered list. The list items are all active (wrapped in <a href="#"> </a>) which is essential for this list to work. Some CSS rules are written exclusively for the "a" element within the list items. For this example a "#" is used as a dummy link.

Step 2 - Remove the bullets


To remove the HTML list bullets, set the "list-style-type" to "none". #navcontainer ul { list-style-type: none; }

Step 3 - Remove padding and margins


Standard HTML lists have a certain amount of left-indentation. The amount varies on each browser. Some browsers use padding (Mozilla, Netscape, Safari) and others use margins (Internet Explorer, Opera) to set the amount of indentation. To remove this left-indentation consistently across all browsers, set both padding and margins to "0" for the "UL". #navcontainer ul { margin: 0; padding: 0; list-style-type: none; }

Step 4 - Display inline


To force the list into one line, apply "display: inline;" to the "LI". CSS CODE #navcontainer ul { margin: 0; padding: 0; list-style-type: none; }

#navcontainer ul li { display: inline; }

Step 5 - Removing text decoration


At this point you may wish to remove the text underline. It is a common practise for navigation not to have underlines as their placement and other feedback mechanisms make them more obviously links. However, you should be aware that modifying standard hyperlink behaviour (such as underlines) can be confusing for some users, who may not realise that the item is a link. #navcontainer ul { margin: 0; padding: 0; list-style-type: none; } #navcontainer ul li { display: inline; } #navcontainer ul li a { text-decoration: none; }

Step 6 - Padding around list items


To make each list item into a box, we need to add padding to the "a" element. #navcontainer ul { margin: 0; padding: 0; list-style-type: none; } #navcontainer ul li { display: inline; } #navcontainer ul li a { text-decoration: none; padding: .2em 1em; }

Step 7 - Adding background color


At this point a background color and border can be applied. There are many combinations of border and background colors that can be used. #navcontainer ul { margin: 0; padding: 0; list-style-type: none; } #navcontainer ul li { display: inline; }

#navcontainer ul li a { text-decoration: none; padding: .2em 1em; color: #fff; background-color: #036; }

Step 8 - Add a rollover color


Use "a:hover" to set a second background color, as a rollover. Roll over the list now you will see how it works. #navcontainer ul { margin: 0; padding: 0; list-style-type: none; } #navcontainer ul li { display: inline; } #navcontainer ul li a { text-decoration: none; padding: .2em 1em; color: #fff; background-color: #036; } #navcontainer ul li a:hover { color: #fff; background-color: #369; }

Step 9 - Center the list


#navcontainer ul { margin: 0; padding: 0; list-style-type: none; text-align: center; } #navcontainer ul li { display: inline; } #navcontainer ul li a { text-decoration: none; padding: .2em 1em;

color: #fff; background-color: #036; } #navcontainer ul li a:hover { color: #fff; background-color: #369; }

the "display" property


display is CSS's most important property for controlling layout. Every element has a default display value depending on what type of element it is. The default for most elements is usually block or inline. A block element is often called a block-level element. An inline element is always just called an inline element.

block <div> div is the standard block-level element. A block-level element starts on a new line and stretches out to the left and right as far as it can. Other common block-level elements are p and form, and new in HTML5 are header, footer, section, and more. </div>

inline span is the standard inline element. An inline element can wrap some text inside a paragraph <span> like this </span> without disrupting the flow of that paragraph. Thea element is the most common inline element, since you use them for links.

none Another common display value is none. Some specialized elements such as scriptuse this as their default. It is commonly used with JavaScript to hide and show elements without really deleting and recreating them. This is different from visibility. Setting display to none will render the page as though the element does not exist. visibility: hidden; will hide the element, but the element will still take up the space it would if it was fully visible.

other display values There are plenty of more exotic display values, such as list-item and table. Here is an exhaustive list. We'll discuss inline-block and flex later on.

extra credit As I mentioned, every element has a default display type. However, you can alwaysoverride this! Though it wouldn't make sense to make an inline div, you can use this to customize the display of elements that have particular semantics. A common example is making inline li elements for horizontal menus.

SS Inline Elements
Inline elements are distinct from block level elements. Whereas block-level elements modify the flow of any text around them, inline elements are designed to flow with the text. Also, inline elements do not have a line break before and after. Properties of inline elements: they flow with text. they have line-height. the element height and width is dependent on the content and will not collapse to the borders of the parent element. So what does all this mean?! It can be displayed in the following way: Green Line - the content area Red Line - the border. The distance between border and content area is the padding area. Blue Line - the element edge. The distance between border and element edge is the margin.

Block vs Inline display style in CSS HTML elements can be displayed either in block or inline style.
The difference between these is one of the most basic things you need to know in order to use CSS effectively. The 3 ways that HTML elements can be displayed All HTML elements are naturally displayed in one of the following ways: Block: Takes up the full width available, with a new line before and after (display:block;) Inline :Takes up only as much width as it needs, and does not force new lines (display:inline;) Not displayed: Some tags are not visible (display:none;)
Block example <p> tags and <div> tags are naturally displayed block-style. (I say "naturally" because you can override the display style by setting the CSS display property e.g. display:inline;.) A block-display element will span the full width of the space available to it, and so will start on a new line in the flow of HTML. The flow will continue on a new line after the block-display element. Here I've started a paragraph and now I'm going to insert a <div> new div inside my paragraph and then continue the text here... See how the <div> jumped in and took over the full width of the space?

Common HTML elements that are naturally block-display include:

<div> Your general-purpose box <h1> ... <h6> All headings <p> Paragraph <ul>, <ol>, <dl> Lists (unordered, ordered and definition) <li>, <dt>, <dd> List items, definition list terms, and definition list definitions <table> Tables <blockquote> Like an indented paragraph, meant for quoting passages of text <pre> Indicates a block of preformatted code <form> An input form

Inline example Inline-display elements don't break the flow. They just fit in with the flow of the document. So here I've got a paragraph going on, and I'm going to add a <span> tag that has a yellow background and italic text. See how it just fits right in with the flow of the text? More elements are naturally inline-style, including:
<span> Your all-purpose inline element <a> Anchor, used for links (and also to mark specific targets on a page for direct linking) <strong> Used to make your content strong, displayed as bold in most browsers, replaces the narrower (bold) tag <em> Adds emphasis, but less strong than . Usually displayed as italic text, and replaces the old (italic) tag <img /> Image <br> The line-break is an odd case, as it's an inline element that forces a new line. However, as the text carries on on the next line, it's not a block-level element. <input> Form input fields like and <abbr> Indicates an abbr. (hover to see how it works) <acronym> Working much like the abbreviation, but used for things like this TLA. You change the display property of any elements Although each HTML element has its natural display style, you can over-ride these in CSS.

This can be very useful when you want your page to look a particular way while using semantically-correct HTML. Examples Say you want to provide a list of items, but you don't want a big bulleted list. You just want to say that you're going to the store to buy: some fizzy drinks, a chainsaw, and some nylon stockings. Or maybe you want a nice toolbar, which is stricly a list (of links) and so should be marked up as a . Here's the code
<ul> <li><a <li><a <li><a <li><a <li><a href="#">Home</a></li> href="#">About us</a></li> href="#">Products</a></li> href="#">FAQs</a></li> href="#">Contact us</a></li>

</ul>

PHP and HTML Radio Buttons

A Radio Button is a way to restrict users to having only one choice. Examples are : Male/Female, Yes/No, or answers to surveys and quizzes. Here's a simple from with just two radio buttons and a Submit button: Make sure you save your work as radioButton.php, as that's where we're posting the Form to itself. To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML form elements. In the HTML above, the NAME of the Radio buttons is the same "gender". The first Radio Button has a value of "male" and the second Radio Button has a value of female. When you're writing your PHP code, it's these values that are returned. Here's some PHP code. Add it to the HEAD section of your HTML: <?PHP $selected_radio = $_POST['gender']; print $selected_radio; ?> This is more or less the same code as we used for the text box! The only thing that's changed (apart from the variable name) is the NAME of the HTML form element we want to access "gender". The last line just prints the value to the page. Again, though, we can add code to detect if the user clicked the Submit button: if (isset($_POST['Submit1'])) { $selected_radio = $_POST['gender']; print $selected_radio; } Again, this is the same code you saw earlier just access the form element called 'Submit1' and see if it is set. The code only executes if it is. Try out the code. Select a radio button and click Submit button. The choice you made is printed to the page - either "male" or "female". What you will notice, however, when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. Again, PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little more complex than for text boxes Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it: The PHP code: <?PHP $male_status = 'unchecked';

$female_status = 'unchecked'; if (isset($_POST['Submit1'])) { $selected_radio = $_POST['gender']; if ($selected_radio = = 'male') { $male_status = 'checked'; } else if ($selected_radio = = 'female') { $female_status = 'checked'; }} ?> The HTML FORM code: <FORM name ="form1" method ="post" action ="radioButton.php"> <Input type = 'Radio' Name ='gender' value= 'male' <?PHP print $male_status; ?> >Male <Input type = 'Radio' Name ='gender' value= 'female' <?PHP print $female_status; ?> >Female <P> <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button"> </FORM> Did we say a little more complex? OK, it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first: <?PHP print $female_status; ?> This is just a print statement. What is printed out is the value inside of the variable. What is inside of the variable will be either the word "checked" or the word "unchecked". Which it is depends on the logic from our long PHP at the top of the page. Let's break that down. First we have two variables at the top of the code: $male_status = 'unchecked'; $female_status = 'unchecked'; These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit button being clicked. Next we have our check to see if Submit is clicked: if (isset($_POST['Submit1'])) { }

Exactly the same as before. As is the next line that puts which radio button was selected into the variable: $selected_radio = $_POST['gender']; We then need some conditional logic. We need to set a variable to "checked", so we have an if, else if construction: if ($selected_radio == 'male') {} else if ($selected_radio == 'female') { } All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one thing; if it's 'female', do another. But look at what we're doing: if ($selected_radio == 'male') { $male_status = 'checked'; } else if ($selected_radio = = 'female') { $female_status = 'checked'; } If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'. So the code works because of the values inside of two variables: $male_status and$female_status. Yes, the code is very messy but radio Buttons can be a quite tricky, when you want to retain the value of the selected item. Speaking of tricky checkboxes are up next!
PHP and HTML Checkboxes Like Radio buttons, checkboxes are used to give visitors a choice of options. Whereas Radio Buttons restrict users to only one choice, you can select more than one option with Checkboxes. Here's a page that asks users to choose which course books they want to order: As you can see, five items can be selected. Only three are chosen at the moment. When the button is clicked you, as the programmer, want to do at least two things: record which checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of errors. You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding. The same is true for checkboxes. Let's have a look at one solution to the problem. Because the code is a little more complex, we've included it in the files you downloaded. The script you're looking for is checkboxes.php, and is in the scripts folder. Open it up and take a look at the

code. Here it is in full, if you want to copy and paste it: The Checkboxes Script Note one thing about the HTML checkbox elements: they all have different NAME values (ch1, ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME. That's because only one option can be selected with Radio Buttons. Because the user can select more than one option with Checkboxes, it makes sense to give them different NAME values, and treat them as separate entities (but some advocate treating them just like Radio Buttons). In your PHP code, the technique is to check whether each checkbox element has been checked or not. It's more or less the same as for the radio Buttons. First we set up five variable and set them all the unchecked, just like we did before: $ch1 = 'unchecked'; $ch2 = 'unchecked'; $ch3 = 'unchecked'; $ch4 = 'unchecked'; $ch5 = 'unchecked'; The next thing is the same as well: check to see if the Submit button was clicked: if (isset($_POST['Submit1'])) { } Inside of this code, however, we have another isset( ) function: if ( isset($_POST['ch1']) ) { } This time, we're checking to see if a checkbox was set. We need to do this because of a peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is returned! If you try the code without checking if the checkboxes are set, then you'll have to deal with a lot of "Undefined" errors. If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true. If the isset( ) function is true, then our code inside of the if statement gets executed: if ($ch1 == 'net') { $ch1 = 'checked'; } This is yet another If Statement! But we're just checking the value of a variable. We need to know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net' then execute some code. The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The rest of the if statements are the same one for each checkbox on the form. The last thing we need to do is to print the value of the variable to the HTML form: <Input type = 'Checkbox' Name ='ch1' value ="net" <?PHP print $ch1; ?> >Visual Basic .NET Again, this is the same code you saw with the Radio Buttons. The PHP part is: <?PHP print $ch1; ?> So we're just printing what is inside of the variable called $ch1. This will either be "unchecked" or "checked",

There are other solution for checkboxes, but none seem simple! The point here, though, is that to get the job done we used Conditional Logic. How to validate checkboxes using JavaScript Another way to deal with checkboxes, though, is with some JavaScript. The following script was sent to us by Tapan Bhanot. It uses JavaScript to validate the checkboxes before sending it to a PHP script. Note how the checkboxes all have the same name on the HTML form, and that it is being posted to a PHP script called step2.php: PHP Submit buttons In the previous section, you saw how to get text from a textbox when a Submit button on a form was clicked. However, when you first load the page the text still displays. The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute. To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this: if ( isset( $_POST['Submit1'] ) ) { } Now that looks a bit messy! But it actually consists of three parts: if ( ) { } isset( ) $_POST['Submit1'] You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out: if (isset($_POST['Submit1'])) { $username = $_POST['username']; if ($username == "letmein") { print ("Welcome back, friend!");} else {print ("You're not a member of this site");} } Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error! In the next part, you'll see how to submit your form data to a PHP script on a different page.

How to avoid resending data on refresh in php


I have a page "index.php" where i have a link called "add_users.php".In "add_users.php",i accept user information and come back to the same page "index.php" where information comes through post action and gets inserted into the database.When i refresh the page orhit back button,resend box appears.I went through many

solution where they asked me to create third page.I tried doing that as follows:After inserting values in database,I redirected ht page as header('Location:http://mysite.com/thankyou.php, and in thankyou.php I again redirected the page to index.php.But getting warning as Cannot modify header information - headers already sent by.... provide me a better solution. Thank You in advance.

Exceptions
Table of Contents
Extending Exceptions PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception's class is not present) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block. When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler(). In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catchblocks, regardless of whether an exception has been thrown, and before normal execution resumes. The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error. Note: Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Example #1 Throwing an Exception


<?php function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); }

return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', } // Continue execution echo "Hello World\n"; ?> The above example will output: 0.2 Caught exception: Division by zero. Hello World Example #2 Exception handling with a finally block <?php function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } return 1/$x; } try { echo inverse(5) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', } finally { echo "First finally.\n"; } try { echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', } finally { echo "Second finally.\n"; } // Continue execution echo "Hello World\n"; ?> The above example will output: 0.2

$e->getMessage(), "\n";

$e->getMessage(), "\n";

$e->getMessage(), "\n";

First finally. Caught exception: Division by zero. Second finally. Hello World Example #3 Nested Exception <?php class MyException extends Exception { } class Test { public function testing() { try { try { throw new MyException('foo!'); } catch (MyException $e) { // rethrow it throw $e; } } catch (Exception $e) { var_dump($e->getMessage()); } } } $foo = new Test; $foo->testing(); ?> The above example will output: string(4) "foo!"

Extending ExceptionsFAQ: things you need to know about namespaces


[edit] Last updated: Fri, 15 Nov 2013

add a noteUser Contributed Notes Exceptions - [20 notes]

up down

5
sander at rotorsolutions dot nl 4 months ago

Just an example why finally blocks are usefull (5.5) <?php //without catch function example() { try { //do something that throws an exeption } finally { //this code will be executed even when the exception is executed } } function example2() { try { //open sql connection check user as example if(condition) { return false; } } finally { //close the sql connection, this will be executed even if the return is called. } } ?> up down

23
Johan 2 years ago

Custom error handling on entire pages can avoid half rendered pages for the users: <?php ob_start(); try { /*contains all page logic and throws error if needed*/ ... } catch (Exception $e) { ob_end_clean(); displayErrorPage($e->getMessage()); }

?> up down

9
michael dot ochs at gmx dot net 5 years ago

Actually it isn't possible to do: <?php someFunction() OR throw new Exception(); ?> This leads to a T_THROW Syntax Error. If you want to use this kind of exceptions, you can do the following: <?php function throwException($message = null,$code = null) { throw new Exception($message,$code); } someFunction() OR throwException(); ?> up down

4
alex dowgailenko [at] g mail . com 2 years ago

If you use the set_error_handler() to throw exceptions of errors, you may encounter issues with __autoload() functionality saying that your class doesn't exist and that's it. If you do this: <?php class MyException extends Exception { } class Tester { public function foobar() { try {

$this->helloWorld(); } catch (MyException $e) { throw new Exception('Problem in foobar',0,$e); } } protected function helloWorld() { throw new MyException('Problem in helloWorld()'); } } $tester = new Tester; try { $tester->foobar(); } catch (Exception $e) { echo $e->getTraceAsString(); } ?> The trace will only show $tester->foobar() and not the call made to $tester->helloWorld(). In other words, if you pass a previous exception to a new one, the previous exception's stack trace is taken into account in the new exception. up down

1
jon at hackcraft dot net 6 years ago

Further to dexen at google dot me dot up with "use destructors to perform a cleanup in case of exception". The fact that PHP5 has destructors, exception handling, and predictable garbage collection (if there's a single reference in scope and the scope is left then the destructor is called immediately) allows for the use of the RAII idiom. http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization and my own http://www.hackcraft.net/RAII/ describe this. up down

4
ask at nilpo dot com 4 years ago

If you intend on creating a lot of custom exceptions, you may find this code useful. I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new exceptions on the fly. It also overrides the default __toString method with a more thorough one. <?php interface IException { /* Protected methods inherited from Exception class */ public function getMessage(); // Exception message public function getCode(); // User-defined Exception code public function getFile(); // Source filename public function getLine(); // Source line public function getTrace(); // An array of the backtrace() public function getTraceAsString(); // Formated string of trace /* Overrideable methods inherited from Exception class */ public function __toString(); // formated string for display public function __construct($message = null, $code = 0); } abstract class CustomException extends Exception implements IException { protected $message = 'Unknown exception'; // Exception message private $string; // Unknown protected $code = 0; // User-defined exception code protected $file; // Source filename of exception protected $line; // Source line of exception private $trace; // Unknown public function __construct($message = null, $code = 0) { if (!$message) { throw new $this('Unknown '. get_class($this)); } parent::__construct($message, $code); }

public function __toString() { return get_class($this) . " '{$this->message}' in {$this>file}({$this->line})\n" . "{$this->getTraceAsString()}"; } } ?> Now you can create new exceptions in one line: <?php class TestException extends CustomException {} ?> Here's a test that shows that all information is properly preserved throughout the backtrace. <?php function exceptionTest() { try { throw new TestException(); } catch (TestException $e) { echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n"; } catch (Exception $e) { echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n"; } } echo '<pre>' . exceptionTest() . '</pre>'; ?> Here's a sample output: Caught TestException ('Unknown TestException') TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31) #0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException>__construct() #1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest() #2 {main} up down

3
Shot (Piotr Szotkowski) 5 years ago

Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exceptions class is not present*) will continue after that last catch block defined in sequence. If an exception is not caught, a PHP Fatal Error will be issued with an Uncaught Exception message, unless a handler has been defined with set_exception_handler(). These two sentences seem a bit contradicting about what happens when a catch matching the thrown exceptions class is not present (and the second sentence is actually correct). up down

1
Edu 4 months ago

The "finally" block can change the exception that has been throw by the catch block. <?php try{ try { throw new \Exception("Hello"); } catch(\Exception $e) { echo $e->getMessage()." catch in\n"; throw $e; } finally { echo $e->getMessage()." finally \n"; throw new \Exception("Bye"); } } catch (\Exception $e) { echo $e->getMessage()." catch out\n"; } ?> The output is: Hello catch in Hello finally Bye catch out up

down

1
Sawsan 1 year ago

the following is an example of a re-thrown exception and the using of getPrevious function: <?php $name = "Name"; //check if the name contains only letters, and does not contain the word name try { try { if (preg_match('/[^a-z]/i', $name)) { throw new Exception("$name contains character other than a-z AZ"); } if(strpos(strtolower($name), 'name') !== FALSE) { throw new Exception("$name contains the word name"); } echo "The Name is valid"; } catch(Exception $e) { throw new Exception("insert name again",0,$e); } } catch (Exception $e) { if ($e->getPrevious()) { echo "The Previous Exception is: ".$e->getPrevious()>getMessage()."<br/>"; } echo "The Exception is: ".$e->getMessage()."<br/>"; } ?>

up down

1
zmunoz at gmail dot com 3 years ago

When catching an exception inside a namespace it is important that you escape to the global space: <?php namespace SomeNamespace; class SomeClass { function SomeFunction() { try { throw new Exception('Some Error Message'); } catch (\Exception $e) { var_dump($e->getMessage()); } } } ?> up down

1
jazfresh at hotmail.com 7 years ago

Sometimes you want a single catch() to catch multiple types of Exception. In a language like Python, you can specify multiple types in a catch(), but in PHP you can only specify one. This can be annoying when you want handle many different Exceptions with the same catch() block. However, you can replicate the functionality somewhat, because catch(<classname> $var) will match the given <classname> *or any of it's sub-classes*. For example: <?php class class class class

DisplayException extends Exception {}; FileException extends Exception {}; AccessControl extends FileException {}; // Sub-class of FileException IOError extends FileException {}; // Sub-class of FileException

try { if(!is_readable($somefile)) throw new IOError("File is not readable!"); if(!user_has_access_to_file($someuser, $somefile)) throw new AccessControl("Permission denied!"); if(!display_file($somefile)) throw new DisplayException("Couldn't display file!"); } catch (FileException $e) { // This block will catch FileException, AccessControl or IOError exceptions, but not Exceptions or DisplayExceptions. echo "File error: ".$e->getMessage(); exit(1); } ?> Corollary: If you want to catch *any* exception, no matter what the type, just use "catch(Exception $var)", because all exceptions are sub-classes of the built-in Exception. up down

0
chugadie dot geo at yahoo dot com 5 years ago

@webmaster at asylum-et dot com What Mo is describing is bug 44053 (http://bugs.php.net/bug.php?id=44053) in which exceptions cannot be caught if you are using a custom error handler to catch warnings, notices, etc. up down

0
omnibus at omnibus dot edu dot pl 5 years ago

Just to be more precise in what Frank found: Catch the exceptions always in order from the bottom to the top of the Exception and subclasses class hierarchy. If you have class MyException extending Exception and class My2Exception extending MyException always catch My2Exception before MyException. Hope this helps up down

0
hartym dot dont dot like dot spam at gmail dot com 6 years ago

@serenity: of course you need to throw exception within the try block, catch will not watch fatal errors, nor less important errors but only exceptions that are instanceof the exception type you're giving. Of course by within the try block, i mean within every functions call happening in try block. For example, to nicely handle old mysql errors, you can do something like this: <?php try { $connection = mysql_connect(...); if ($connection === false) { throw new Exception('Cannot connect do mysql'); } /* ... do whatever you need with database, that may mail and throw exceptions too ... */ mysql_close($connection); } catch (Exception $e) { /* ... add logging stuff there if you need ... */ echo "This page cannot be displayed"; } ?> By doing so, you're aiming at the don't repeat yourself (D.R.Y) concept, by managing error handling at only one place for the whole. up down

0
fjoggen at gmail dot com 7 years ago

This code will turn php errors into exceptions: <?php

function exceptions_error_handler($severity, $message, $filename, $lineno) { throw new ErrorException($message, 0, $severity, $filename, $lineno); } set_error_handler('exceptions_error_handler'); ?> However since <?php set_error_handler()?> doesn't work with fatal errors, you will not be able to throw them as Exceptions. up down

-3
mike at clove dot com 3 years ago

The PHP documentation has gone from very useful to hideously obstructive. The people who are rearranging the doc into little, tiny chunks which are hyperlinked all over the place obviously never write code. I just spent 10 minutes trying to find the name of an IO Exception so I can use it in some code I'm writing. Old Doc: I would go to the index, click on Exceptions and then scroll down the page (or do a find on IO) and there it would be. 10 seconds tops. New Doc: Go to the index click on Predefined Exceptions Click on Exception - find description of Exception Object - info not there Back Button Click on Error Exception - find description of Generic ErrorExeption object Back Button Click on SPL Exceptions (what the hell is this? - something new?) Look at Table of contents: 13 Exception Categories - none of which looks like an IOException Click on Predefined Exceptions in the See Also Back to Previous Useless Page First You completely screw up the Perl Regular Expression page by chopping it into tiny, obscure chunks and now you destroy the exception documentation. PLEASE put it back the way it was. Or get somebody who actually uses this stuff like a handbook while writing code to fix it

Or shoot somebody. Incredibly frustrated and thinking of rewriting everything in Python, Mike Howard <mike at clove dot com> up down

0
jim at anderos dot com 1 month ago

If you are using a namespace, you must indicate the global namespace when using Exceptions. <?php namespace alpha; function foo(){ throw new \Exception("Something is wrong!"); // throw new Exception(""); will fail } try { foo(); } catch( \Exception $e ) { // catch( Exception $e ) will give no warning, but will not catch Exception echo "ERROR: $e"; } ?> up down

0
sander at rotorsolutions dot nl 4 months ago

Just an example why finally blocks are usefull (5.5) <?php //without catch function example() { try { //do something that throws an exeption } finally { //this code will be executed even when the exception is executed

} } function example2() { try { //open sql connection check user as example if(condition) { return false; } } finally { //close the sql connection, this will be executed even if the return is called. } } up down

0
sander at rotorsolutions dot nl 4 months ago

Just an example why finally blocks are usefull (5.5) <?php //without catch function example() { try { //do something that throws an exeption } finally { //this code will be executed even when the exception is executed } } function example2() { try { //open sql connection check user as example if(condition) { return false; } } finally { //close the sql connection, this will be executed even if the return is called. } }

?> up down

-1
cyrus+php at boadway dot ca 1 month ago

There's some inconsistent behaviour associated with PHP 5.5.3's finally and return statements. If a method returns a variable in a try block (e.g. return $foo;), and finally modifies that variable, the /modified/ value is returned. However, if the try block has a return that has to be evaluated in-line (e.g. return $foo+0;), finally's changes to $foo will /not/ affect the return value. [code] function returnVariable(){ $foo = 1; try{ return $foo; } finally { $foo++; } } function returnVariablePlusZero(){ $foo = 1; try{ return $foo + 0; } finally { $foo++; } } $test1 = returnVariable(); // returns 2, not the correct value of 1. $test2 = returnVariablePlusZero(); // returns correct value of 1, but inconsistent with $test1. [/code] It looks like it's trying to be efficient by not allocating additional memory for the return value when it thinks it doesn't have to, but the spec is that finally is run after try is completed execution, and that includes the evaluation of the return expression. One could argue (weakly) that the first method should be the correct result, but at least the two methods should be consistent.

You might also like