简体   繁体   中英

Quotation marks in PHP / JS / DOM

What is the right way to use quotation marks ?

echo 'string' . $variable . 'anotherstring'; 

or

echo "string" . $variable . "anotherstring";

the problem of course comes to light when we need to print, return, or echo the quotaion mrk itself ...

$output = '<div class="' . $class . ' " style =" ' . $style . ' ">' ;

or

$output = "<div class=' " . $class . " ' style =' " . $style . " '>" ;

??

And what about when some jQuery or Javascript enters the game ??

function o99_print_front_script() {
    return '
    <script type="text/javascript">
var pluginDir = " '. PHP_CONSTANT_X .' " ; 

  var cluster_styles = [{
        url:pluginDir +"/images/marker-o.png",
        background: "#c6c6c6"
        textColor: "#0f0"
    }];

      jQuery(document).ready(function() {
        jQuery("#example").example_func({
          elements:".div_1 .class_2",
           infobox: true,   
        map_opt: {zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP},
        infobox_s:s_infobox_k,
        marker_icon:pluginDir +"/images/image_1.png"
});
});
</script>
    ' ;}

OR

function o99_print_front_script() {
    return "
    <script type='text/javascript'>
var pluginDir = ' ". PHP_CONSTANT_X ." ' ; 

  var cluster_styles = [{
        url:pluginDir +'/images/marker-o.png',
        background: '#c6c6c6'
        textColor: '#0f0'
    }];

      jQuery(document).ready(function() {
        jQuery('#example').example_func({
          elements:'.div_1 .class_2',
           infobox: true,   
        map_opt: {zoom: 3,
        mapTypeId: google.maps.MapTypeId.ROADMAP},
        infobox_s:s_infobox_k,
        marker_icon:pluginDir +'/images/image_1.png'
});
});
</script>
    " ;}

Is there some specification for this ? Some standard ? some "best practice" ?

Browsing through code you can see all kind of examples .

which one should we use for "first level" and which for "second" ? And what if I have to "nest" 3 levels of those ??

this problem highlights itself when one uses some CMS , or system with "plugins" - and then wants to extend it with own code .the resulted HTML code in the DOM gets all confused, and you can not understand which quotes are which especially when JS is involved).

I am aware that all of them will work, but I want to know which one is right and which is wrong (if such terms exists in regarding this).

EDIT I

After reading comments / answers - I have realised that maybe I wrote the question in an unclear fashion. my question is regarding the Outputted xHTML /JS . Of course that it has direct consequences on the PHP part , but mainly I was wondering what is the best practice to maintain a consistent and uniformal code throught the finished document while maintaining an easy syntax on the back-end.. Even looking at the source of this very page here (this stackexchange site) one can see some inconsistent behavior (at least to me it looks like it )

About markup nesting I would strongly suggest to adopt the MVC pattern so you will obtain a clear separation of the view (your html template) from the controller part (what you have to put in the template). In this way you can avoid to make a "soup" of unmantainable markup and php code

Anyway for the markup part I prefer writing like so

echo "string $variable anotherstring";

since PHP variables are parsed when included in a string with double-quote delimiters. For long code blocks like the javascript part another possibility is to use HEREDOC syntax so you can write php variables like this

$jssnippet = <<<EOJS
   <script type='text/javascript'>
   var pluginDir = '{$PHP_CONSTANT_X}' ; 
   ...
EOJS;

See also http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc hope this helps

如果您使用双引号,PHP将尝试评估字符串中的内容,因为如果您使用单引号的速度更快,则将单引号视为文字,以确保性能。

look at this example

  echo "<a href='javascript:dosomething(\"isn\'t it a good day?\");'></a>";

The main idea is the inner quote must not interfere with the parent ones.

There are quite a few ways to declare and use string literals . It doesn't take long before you start mixing all such methods in your code. I personally prefer using double quoted strings almost everywhere, even if it requires me to write:

"<div foo=\"" . bar() . "\">\$blah</div>";

Double quoted strings allow you to use variables inside strings.

As for the example you mentioned above, there are better, more readable ways to do that, for example:

function k99_print_front_script() {
    ob_start();
    ?>
    <script type='text/javascript'>
        var pluginDir = '<?php echo PHP_CONSTANT_X; ?>'; 
        var cluster_styles = [{
            url:pluginDir +'/images/marker-o.png',
            background: '#c6c6c6'
            textColor: '#0f0'
        }];
        jQuery(document).ready(function() {
            jQuery('#example').example_func({
                elements:'.div_1 .class_2',
                infobox: true,   
                map_opt: {zoom: 3,
                mapTypeId: google.maps.MapTypeId.ROADMAP},
                infobox_s:s_infobox_k,
                marker_icon:pluginDir +'/images/image_1.png'
            });
        });
    </script>
    <?php
    return ob_get_clean();
}

As for your question about whether a standard exists or not, I was looking at a couple of PHP code formatters which brought me to this page: PEAR Manual -- Coding Standards . I failed to find recommendation about strings, although the examples consistently used ' enclosed strings.

for php it makes a difference whether you use " or ' . ' is more performant than " because it won't parse the string to check for variables to substitute.

As for Javascript - use the ones you like... JS doesn't care. This makes it easy if you need to use quotes inside strings, simply use both var mystring = "I said 'Hello World!'"; .

For HTML and Javascript it's down to preference, but PHP is different.

In HTML, tag attributes can be either double or single quotes - this is defined in the spec . If you check page sources, most people seem to use double quotes, but there is nothing to stop you using single quotes.

In Javascript there is no reason to use one more than the other - indeed, usage seems to be pretty split. One consideration that you've noted, is that if you're double quoting your HTML attributes, then single quoting your Javascript strings means you can use inline Javascript without breaking your normal style. Eg <a href="alert('Hello, world')"> . A good introduction is available here .

PHP is different however. Double quoted strings are parsed for variables, requiring additional overhead. It's not going to be a massive drain, but it's certainly good practice. In PHP

$string = 'This is my ' . $variable;

and

$string = "This is my $variable";

produce equivalent output. For that reason, it is more efficient to use single quoted strings in PHP, or learn to use double quoted string syntax when necessary.

In the end, it's entirely up to you, but these are the norms. You won't be penalised if you stray from standard usage, but it's important to understand the full implications, especially with PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM