Avatar

How can I put the php-code in an function?

1
2
3
4
5
6
7
8
9
10
11
<input id="username" name="username" type="text" size="30" value="<?php 
    if (isset($_POST['username'])) {
	echo $_POST['username'];
        }
    elseif (isset($_SESSION['username'])) {
	echo $_SESSION['username']; 
	}
    else {
	echo "Username"; 
	} 
?>" />

Refactorings

No refactoring yet !

Ad2ffc6b05fb4390643f36a258b86362

slaskis

November 25, 2007, November 25, 2007 15:51, permalink

2 ratings. Login to rate!

Long time ago i coded any php so i'm not sure this is valid code, but maybe something like this?

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function has( var , default ) {
  if( isset( $_POST[var] )
    return $_POST[var];
  elseif( isset( $_SESSION[var] )
    return $_SESSION[var];
  else
    return default;
}
?>

<input id="username" name="username" type="text" size="30" value="<?=has('username','Username');?>" />
54cb150c98bc09e66324263887554a05

BetaDevil

November 25, 2007, November 25, 2007 16:50, permalink

1 rating. Login to rate!
1
2
3
4
5
6
<?php
$username = (isset($_POST['username'])) ? $_POST['username'] : (isset($_SESSION['username'])) ? $_SESSION['username'] : 'Username';
?>

echo '<input id="username" name="username" type="text" size="30" value=' . $username . '" />';
<input id="username" name="username" type="text" size="30" value=<?= $username ?>" />
5a00a3a98dcf6f9cd717440fd2b606e5

Eineki

November 26, 2007, November 26, 2007 23:00, permalink

No rating. Login to rate!

I prefer heredoc (http://www.php.net/manual/en/language.types.string.php #language.types.string.syntax.heredoc),

You can set all the variables you need in the first part of the script and concentrate on the layout in the second part
without worrying of single or double quotes and using the graph parenthesis to enclose the variables.

1
2
3
4
5
6
7
8
9
<?php
$username = (isset($_POST['username'])) ? $_POST['username'] : (isset($_SESSION['username'])) ? $_SESSION['username'] : 'Username';

echo <<< EXAMPLE

  <input id="username" name="username" type="text" size="30" value="{$username}" />

EXAMPLE;
?>

Your refactoring





Format Copy from initial code

or Cancel