防止PHP在源代码中解释字符串中的新行


Prevent PHP Interpreting New Lines in Strings in the Source Code

我经常不得不为变量分配大字符串。在源代码中,我最好将行数控制在80个字符以内。

理想情况下,我希望能够将这些文字字符串放在多行上。

我想避免的是使用串联或函数调用(例如preg_replace())将多个字符串连接在一起。我不喜欢为了改进代码的风格而必须调用语言特性的想法。

我想要的示例:

    $text = <<<TEXT
Line 1
Line 2
Line 3
TEXT;
    echo($text);

这应该输出:

Line1Line2Line3

这可能吗?

有几个选项:

  1. 只需连接(首选)

  2. 使用array构建

  3. 使用sprintf()

仅连接:

echo 'long long line1'
    . 'another long line 2'
    . 'the last very long line 3';

效率如何?

上面的代码编译成以下操作码(这就是运行的操作码):

5    0  >   CONCAT      ~0      'long+long+line1', 'another+long+line+2'
     1      CONCAT      ~1  ~0, 'the+last+very+long+line+3'
     2      ECHO        ~1

正如您所看到的,它通过连接前两行和最后一行来构建字符串;则最终丢弃CCD_ 4。就记忆而言,这种差异可以忽略不计。

这就是单个echo语句的样子:

3    0  >   ECHO                'long+long+line1another+long+line+2the+last+very+long+line+3'

从技术上讲,它更快,因为没有中间步骤,但实际上你根本不会感觉到这种差异。

使用array:

echo join('', array(
    'line 1',
    'line 2',
    'line 3',
));

使用sprintf():

echo sprintf('%s%s%s',
    'line 1',
    'line 2',
    'line 3'
);
$text = 'Line1'.
        'Line2'.
        'Line3';
var_dump($text);

通过这种方式,您可以将代码拆分为几行,但数据本身是一行。

有很多方法可以连接字符串,但问题不在于字符串的长度,也不在于对其进行格式化。您将大量标记与php混合在一起。

IMO真的,如果你的应用程序的核心逻辑包含大量的html,那么你可能应该考虑将其从逻辑中移出,并从外部文件加载,这样可以提高代码的可读性。

/your_view.php

<h1>This is my view, I only want small amounts of PHP here, values will be passed to me</h1>
<p><?php echo $somevar;?></p>

现在,在您的核心逻辑中,您可能会有一个全局函数来加载视图并将数据传递给它。然后,您可以控制新行的删除。

index.php(或此类逻辑文件)

<?php
function load_view($path,$data,$minify=false) {
    if (file_exists($path) === false){
        return false;
    }
    extract($data);
    ob_start();
    require($path);
    $out = ob_get_contents();
    ob_end_clean();
    //you can remove all the new lines here
    if($minify===true){
        return preg_replace('/^'s+|'n|'r|'s+$/m', '', $out);
    }else{
        return $out;
    }
}
$data = array('somevar'=>'This is some data that I want to pass to a block of html');
echo load_view('./your_view.php',$data,true);
?>