Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php .com


Regarding earlier note by @purkrt :

> I would like to stress out that the opening tag is "<?php[whitespace]", not just "<?php"

This is absolutely correct, but the wording may confuse some developers less familiar with the extent of the term "[whitespace]".

Whitespace, in this context, would be any character that generated vertical or horizontal space, including tabs ( 	 ), newlines ( 
 ), and carriage returns ( 
 ), as well as a space character ( s ). So reusing purkrt's example:

<?php/*blah*/ echo "a"?> 

would not work, as mentioned, but :

<?php /*php followed by space*/ echo "a"?>

will work, as well as :

<?php
/*php followed by end-of-line*/ echo "a"?>

and :

<?php    /*php followed by tab*/ echo "a"?>

I just wanted to clarify this to prevent anyone from misreading purkrt's note to mean that a the opening tag --even when being on its own line--required a space ( s ) character. The following would work but is not at all necessary or how the earlier comment should be interpreted :

<?php 
/*php followed by a space and end-of-line*/ echo "a"?>

The end-of-line character is whitespace, so it is all that you would need.
Comment

php .com


<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
Comment

php .com


"<script language="php"> </script>, are always available." since PHP 7.0.0 is no longer true. These are removed along the ASP "<%, %>, <%=" tags.
Comment

php .com

<?php
$foo = "1";  // $foo is string (ASCII 49)
$foo *= 2;   // $foo is now an integer (2)
$foo = $foo * 1.3;  // $foo is now a float (2.6)
$foo = 5 * "10 Little Piggies"; // $foo is integer (50)
$foo = 5 * "10 Small Pigs";     // $foo is integer (50)
?>
Comment

php .com

<?php
$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();
?>
Comment

php .com

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>
Comment

php .com


One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
  $file_contents  = '<?php die(); ?>' . "
";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
//  $file_contents  = '<?php die(); ?>' . "
";
?>

Which results in ' . "
"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
  $file_contents  = '<' . '?php die(); ?' . '>' . "
";
?>

Comment

php .com


<?php
 /*
    echo 'This is a test'; /* This comment will cause a problem */
 */
?>

Comment

php .com


<?php
    echo 'This is a test'; // This is a one-line c++ style comment
    /* This is a multi line comment
       yet another line of comment */
    echo 'This is yet another test';
    echo 'One Final Test'; # This is a one-line shell-style comment
?>

Comment

php .com


it's perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as <?php echo 'something'; //comment ?>

<?php
if(1==1)
{
    //?>
}
?>

i discovered this "anomally" when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match('/^(?>c|b)at$/', 'cat', $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don't know about # style comments, i don't ever personally use them.
Comment

php .com


A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
<?php
//*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>

Now by taking out one / on the first line..

<?php
/*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even "flip" two blocks, like this:
<?php
//*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
vs
<?php
/*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>

Comment

php .com


It is worth mentioning that, HTML comments have no meaning in PHP parser. So,

<!-- comment
<?php echo some_function(); ?>
-->

WILL execute some_function() and echo result inside HTML comment.
Comment

php .com


Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it's easy for the next person to read. So something like this might help...

<?php

//======================================================================
// CATEGORY LARGE FONT
//======================================================================

//-----------------------------------------------------
// Sub-Category Smaller Font
//-----------------------------------------------------

/* Title Here Notice the First Letters are Capitalized */

# Option 1
# Option 2
# Option 3

/*
 * This is a detailed explanation
 * of something that should require
 * several paragraphs of information.
 */
 
// This is a single line quote.
?>

Comment

php .com


Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
<?php
/**
* The second * here opens the DocBook commentblock, which could later on<br>
* in your development cycle save you a lot of time by preventing you having to rewrite<br>
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie <br> tags) to create something of a layout.
Comment

php .com


Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won't hurt me ;-)

<?php 

/*

 $f->setPattern('/^d.*/');

*/

?>

Comment

php .com


Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment ;)

<?php

// Control
echo microtime(), "<br />"; // 0.25163600 1292450508
echo microtime(), "<br />"; // 0.25186000 1292450508

// Test
echo microtime(), "<br />"; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime(), "<br />"; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).
Comment

php .com


<h1>This is an <?php # echo 'simple';?> example</h1>
<p>The header above will say 'This is an  example'.</p>
Comment

php .com

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
Comment

php .com

<?php
class MyClass {
    const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0

echo MyClass::CONST_VALUE;
?>
Comment

php .com

<?php
$foo = 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
echo $foo;                 // $foo is altered too.
?>
Comment

php .com

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.
?>
Comment

php .com

<?php
class foo
{
    function do_foo()
    {
        echo "Doing foo."; 
    }
}

$bar = new foo;
$bar->do_foo();
?>
Comment

php .com

<?php

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    } 
}

?>
Comment

php .com

<?php
$array = array(
    1    => "a",
    "1"  => "b",
    1.5  => "c",
    true => "d",
);
var_dump($array);
?>
Comment

php .com


MSpreij (8-May-2005) says  /* .. */ overrides //  
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with: 
   //  then /* and */ are "overridden" until after end-of-line 
   /*  then // is "overridden" until after */
Comment

php .com

<?php
$a = 1.234; 
$b = 1.2e3; 
$c = 7E-10;
$d = 1_234.567; // as of PHP 7.4.0
?>
Comment

php .com

<?php
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
$a = 1_234_567; // decimal number (as of PHP 7.4.0)
?>
Comment

php .com

<?php
$foo = True; // assign the value TRUE to $foo
?>
Comment

php .com


a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli's comment from nov'05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in:  just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out,,,, but hey, to each their own :)

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include :)

for example, placed at top of file:

<?php $ver3 = TRUE;  
       $debug2 = FALSE; 
?> 

and then deeper inside the file: 

<?php if ($ver3) {
           print("This code is included since we are testing version 3");
         }
?>

<?php if ($debug2) {
           print("This code is 'commented' out");
         }
?>

Comment

php .com


Playing around with different open and close tags I discovered you can actually mix different style open/close tags

some examples

<%
//your php code here
?>

or

<script language="php">
//php code here
%>
Comment

php .com


At the end of each statement,we will use a semicolon to seperate each statement.Php closing tag autometically implies a semiclon.So last line of a statment do not require a statement.

<?php echo "first statement";
      echo "second statement"
?>

Closing tag is optional and some cases omitting the closing tag is very helpful.
1.using include or require function
2.unwanted whitespace will not occur at the end of file
3.add header any time

<?php echo "omitting closing tag";

Comment

php .com


When the PHP interpreter hits the ?> closing tags, it WON'T output right away if it's inside of a conditional statement:
(no matter if it's an Alternative Syntax or not)

<html>
<?php
$a = 1;
$b = 2;
if ($a === 1) {
    if ($b == 2) {
        ?><head></head><?php
    } else {
        ?><body></body><?php
    }
}
?>
</html>

This would output `<html><head></head></html>`.
Aside from conditional statements, the PHP interpreter also skip over functions! What a surprise!

<html>
<?php
function show($a) {
    ?>
    <a href="https://www.<?php echo $a ?>.com">
    Link
    </a>
    <?php
}
?>
<body>
    <?php show("google") ?>
</body>
</html>

This gives `<html><body><a href="https://www.google.com">Link</a></body></html>`.
These really confused me, because at first I thought it would output any HTML code right away, except for Alternative Syntaxes (https://www.php.net/manual/en/control-structures.alternative-syntax.php). There are more strange cases than I thought.
Comment

php .com


When php parse a file,it looks for opening and closing tag.php parser interpreting  the code between opening and closing tag and allows php to be embedded in all shorts of different documents.Outside of opening and closing tag is ignored by the php parser.

Now php recommended you to use only two tags.

1.Standard tag which is <?php echo "I'm Standard tag"; ?>
2.Short echo tag which is <?= "I'm Short echo tag"; ?>

Both are not affected by php ini configuration file directive.

Although php also allow short open tag which is discoursed but still available if php was configured with --enable-short-tags or  short_open_tag is enabled in php ini configuration file directive.

if you want to use php in combination with xml,you can disable short_open_tag in order to use <?xml ?> inline.
 Otherwise, you can print it with PHP, for example: <?php echo '<?xml version="1.0"?>'; ?>

short_echo_tag also affected the short echo tag before 5.4.0
since 5.4.0,short echo tag is always available.

asp tag <% %> and <%= > are removed from php 7
script tag <script language="php"> <script/> also removed from php 7

It is preferable to omit the closing tag if a file only contain the php code.
<?php echo "a statement"; 
      echo "another statement";

It prevent unwanted whitespace or new line being added after the closing tag.
--happy-gazi|php-

Comment

php .com


<?php if ($expression == true): ?>
  This will show if the expression is true.
<?php else: ?>
  Otherwise this will show.
<?php endif; ?>

Comment

php .com


Do not mis interpret

<?php echo 'Ending tag excluded'; 

with

<?php echo 'Ending tag excluded';
<p>But html is still visible</p>

The second one would give error. Exclude ?> if you no more html to write after the code.
Comment

php .com


When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
Comment

php .com


1.  <?php echo 'if you want to serve PHP code in XHTML or XML documents,
                use these tags'; ?>

2.  You can use the short echo tag to <?= 'print this string' ?>.
    It's always enabled in PHP 5.4.0 and later, and is equivalent to
    <?php echo 'print this string' ?>.

3.  <? echo 'this code is within short tags, but will only work '.
            'if short_open_tag is enabled'; ?>

4.  <script language="php">
        echo 'some editors (like FrontPage) don't
              like processing instructions within these tags';
    </script>
    This syntax is removed in PHP 7.0.0.

5.  <% echo 'You may optionally use ASP-style tags'; %>
    Code within these tags <%= $variable; %> is a shortcut for this code <% echo $variable; %>
    Both of these syntaxes are removed in PHP 7.0.0.
Comment

php .com


Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:

<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>

When the above code snippet is executed we get the following output:

Hello, there!
Hello, there!
Hello, there!
Hello, there!
Comment

php .com


Version of  7.0.0,3 tags are available in php.
1.long form tag (<?php ?>)
2.short echo tag(<?= ?>)
3.short_open_tag(? ?)
You can use short_open_tag when you start xml with php.
Comment

php .com


In php there are 3 types of comments
1.single line c++ style comment(//)
2.single line Unix shell stype comment(#)
3.multi line c style comment(/*/)

single or multi line comment comes to the end of the line or come first to the current block of php code.

HTML code will be printed after //...?> or #...?>
closing tag breaks the php mode and return to html mode.

different comments in different tags:
===================================
 <H1>Standard tag: <?php //echo " standard tag"; ?>single line c++ style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Standard tag:single line c++ style comment'</p>

 <H1>Standard tag: <?php # echo " standard tag"; ?>single line unix shell style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Standard tag:single line unix shell style comment'</p>

 <H1>Standard tag: <?php /*echo " standard tag"; */?>multi line c style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Standard tag:multi line c style comment'</p>

  <H1>short echo tag: <?= // " short echo tag"; ?>single line c++ style comment</H1>
 <p>The header above will break php mode show a unexpected syntex error'</p>

  <H1>short echo tag: <?= #  " short echo tag"; ?>single line c++ style comment</H1>
 <p>The header above will break php mode show a unexpected syntex error'</p>

  <H1>short echo tag: <?= /*echo " short echo tag"*/ ; ?>multiple  line c style comment</H1>
 <p>The header above will break php mode show a unexpected syntex error'</p>

 <H1>Short tag: <? //echo " short tag";?>single line c++ style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Short tag:single line c++ style comment'</p>

  <H1>Short tag: <? #echo " short tag";?>single line unix shell style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Short tag:single line unix shell style comment'</p>

   <H1>Short tag: <? /* echo " short tag";*/?>multi line c style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Short tag:multi line c style comment'</p>

    <H1>Script tag: <script language="php"> // echo " script tag";</script>single line c++ style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Script tag:single line c++ style comment'</p>

    <H1>Script tag: <script language="php"> /* echo " script tag";*/</script>multi line c style comment</H1>
 <p>The header above will break php mode and return html mode and show  'Script tag:multi line c style comment'</p>

    <H1>Script tag: <script language="php"> # echo " script tag";</script>single line unix shell style comment</H1>
 <p>The header above will not break php mode </p>
Comment

php .com


It's possible to write code to create php escapes which can be processed later by substituting x3f for '?' - as in echo "<x3fphp echo 'foo'; x3f>";

This is useful for creating a template parser which later is rendered by PHP.
Comment

php .com


<?php
    echo 'This is a test';
?>

<?php echo 'This is a test' ?>

<?php echo 'We omitted the last closing tag';

Comment

php .com


<p>This is ignore by the php parser and displayed by the browser </p>

 <?php echo "While this is going to be parsed"; ?>

 <?php 

when php interpreter hits the closing tag it start to outputing everything whatever it finds until it hit another opening tag.If php interpreter find a conditional statement in the middle of a block then php interpreter decided which block skip  

 Advanced escaping using conditions

  <?php $a = 10; if($a<100): ?>
  This conditional block is executed
  <?php else: ?>
      otherwise this will be executed
      <?php endif; ?>

In php 5 version,there are 5 opening and closing tags.
1.<?php echo "standard long form php tag and if you use xml with php this tag will be use";?>

2.<?= "short echo tag and alwayes available from 5.4.0";?>

3.<? echo "short open tag which is available if short_open_tag is enable in php ini configuration file directive or php was configured with --enable-short-tags.This tag has discoursed from php 7.If you want to use xml with php,then short_open_tag in php ini will be disabled";?>

4.<script language="php">
echo "Some editor do not like processing the code within this tag and this tag is removed from php 7.0.0 version";

</script>

5.<% echo "asp style tag and asp_tags should be enabled but now php 7.0.0 version,this tag is removed";%>
Comment

php .com


These methods are just messy. Short-opening tags and ASP-styled tags are not always enabled on servers. The <script language="php"></script> alternative is just out there. You should just use the traditional tag opening:

<?php?>

Coding islands, for example:

<?php
$me =  'Pyornide';
?>
<?=$me;?> is happy.
<?php
$me = strtoupper($me);
?>
<?=$me;?> is happier.

Lead to something along the lines of messy code. Writing your application like this can just prove to be more of an 
inconvenience when it comes to maintenance.

If you have to deal chunks of HTML, then consider having a templating system do the job for you. It is a poor idea to rely on the coding islands method as a template system in any way, and for reasons listed above.
Comment

php .com


If you are using editor with code highlight, it’s much easier to notice error like /* */ */.
Comment

php .com

<?php
$large_number = 2147483647;
var_dump($large_number);                     // int(2147483647)

$large_number = 2147483648;
var_dump($large_number);                     // float(2147483648)

$million = 1000000;
$large_number =  50000 * $million;
var_dump($large_number);                     // float(50000000000)
?>
Comment

php .com

<?php

$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// Outputs 51
var_export($fn(5)(10));
?>
Comment

php .com

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>
Comment

PREVIOUS NEXT
Code Example
Php :: deleting a database in phpmyadmin 
Php :: phpexcel 
Php :: Symfony Expected argument of type "string", "null" given 
Php :: inner pages not found yii 
Php :: laravel imap - Set message flags 
Php :: laravel admin disable batch selection 
Php :: preared request pdo 
Php :: wherenotnull laravel 
Php :: yii2 change transport 
Php :: how to convert amount in words in php 
Php :: laravel dynamically add remove table row 
Php :: replace special characters from string in codeigniter 
Php :: php call static method from class 
Php :: wordpress html classes 
Php :: how to pass value in app.blade 
Php :: php file request 
Php :: custom end-point request php-salesforce-rest-api 
Php :: pass variable in laravel ancher tag laravel 8 
Php :: featured image tab not displayed on post 
Php :: rename image file using post id in wordpress programmatically 
Php :: $s = [1,2,3] for loop use in php 
Php :: codeigniter 4 multiple validate error 
Php :: laravel how to generate short link in laravel framework and relation with 3 model 
Php :: laravel relationship example 
Php :: wcfm filter vendor dashboard widgets 
Php :: php curl fail verbosly 
Php :: phpmyadmin account locked 
Php :: Including ACF in a custom theme or plugin 
Php :: removing public from laravel url 
Php :: phoenix query builder 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =