PDA

View Full Version : Clarify these contructs plz


StupidRalph
04-04-2006, 12:06 PM
I never understood certain language contructs (I'm not sure if they are constructs) and did not know how to research them appropiately. Things like the combinated use of the questionmark and colon. Or when using sprintf the %s (and others). The "@" before certain functions and variables.

Let me give an examples:

The combinated use of "?" and ":".
$_POST['username']) ? $_POST['username'] : null )

The %s,%c, etc.
sprintf(%s,)
I know that this is just a type identifier but never really understood it totally.

The @ before variables
<?php @$_SESSION['index'] ?>

Kakao
04-04-2006, 12:36 PM
The ternary operator code you supplied is missing the condition.

A complete example

$a = $b == $c ? $d : $e

Is the same as:

if ($b == $c) $a = $d;
else $a = $e;

Programming Crash Course (http://programming-crash-course.com/)

StupidRalph
04-04-2006, 12:44 PM
Thank you for clarifying that one up...I kind've seen that but this makes it clear for me..

Kakao
04-04-2006, 12:56 PM
The @ operator supresses error messages generated by an expression:

<?php
$infinite = 1/0;
?>

That 1/0 generates this message:
Warning: Division by zero in /var/www/html/teste/at.php on line 2

The next 1/0 is silent, no error message:

<?php
$infinite = @(1/0);
?>

Programming Crash Course (http://programming-crash-course.com/)

degsy
04-04-2006, 02:34 PM
sprintf can be used where you want to use variables.

e.g.

<?php
$var1 = 'something';
$var2 = 'else';

$sql = sprintf("SELECT * FROM table WHERE field1 = '%s' and field2 LIKE '%%%s'", $var1, $var2);
echo $sql;
?>



Suppressing an error message can be useful if you know that there may be an error and want to give your own error message


if(!@file_get_contents('http://www.google.typo')){
echo 'URL cannot be accessed';
}

StupidRalph
04-04-2006, 03:12 PM
That puts this in perspective for me. Thank you very much.

StupidRalph
04-05-2006, 12:02 PM
I just wanted to add Paamayim Nekudotayim to my list. The double colon (::). The double colon, is a token that allows access to static, constant, and overridden members or methods of a class. (PHP Manual)
More can be read here http://uk2.php.net/manual/en/language.oop5.paamayim-nekudotayim.php .

I've also seen the preceding ampersand before the new key word.
$obj= &new object;
I'm only now beginning to learn how to program OOP but I think that has to do with that. I have read that appending the ampersand before the new creates a reference to an object instead of copying an object. Sorry I don't have a link to explain this.