代码之家  ›  专栏  ›  技术社区  ›  Kendall Hopkins

高尔夫代码:一行PHP语法

  •  10
  • Kendall Hopkins  · 技术社区  · 16 年前

    PHP的语法有一些漏洞,有时在开发过程中程序员会介入其中。这可能会导致很多挫折,因为这些语法漏洞似乎无缘无故地存在。例如,不能轻易地创建一个数组并在同一行上访问该数组的任意元素( func1()[100] 不是有效的PHP语法)。解决这个问题的方法是使用一个临时变量并将语句分成两行,但有时这会导致非常冗长、笨拙的代码。

    我知道其中有几个洞(我肯定还有更多)。这是很难想出一个解决方案,更不用说在一个代码高尔夫风格。获胜者是四个语法漏洞的字符总数最少的人。

    规则

    1. $output = ...; ... 不包含任何 ; 的。
    2. eval 允许的)
    3. 语句的工作方式与非工作语法的假定函数相同(即使在失败的情况下也是如此)。
    4. 语句必须在没有任何语法错误的情况下运行 E_STRICT | E_ALL

    1. $output = func_return_array()[$key]; -访问任意偏移量( string integer )函数的返回数组
    2. $output = new {$class_base.$class_suffix}(); -用于创建新类的任意字符串连接
    3. $output = {$func_base.$func_suffix}(); -作为函数调用的任意字符串连接
    4. $output = func_return_closure()(); -调用从另一个函数返回的闭包
    2 回复  |  直到 16 年前
        1
  •  8
  •   Shaun    16 年前

    <?php
    
    error_reporting(E_ALL | E_STRICT);
    
    // 1
    function func_return_array() { return array(0 => 'hello'); }
    $key = 0;
    
    $output = ${!${''}=func_return_array()}[$key];
    
    echo '1: ' . $output . "\n";
    
    
    // 2
    class Thing {}
    $class_base = 'Thi'; $class_suffix = 'ng';
    
    $output = new ${!${''}=$class_base.$class_suffix}();
    
    echo '2: ';
    var_dump($output);
    
    
    // 3
    $func_base = 'func_'; $func_suffix = 'return_array';
    
    $output = ${!${''}=$func_base.$func_suffix}();
    
    echo '3: ';
    var_dump($output);
    
    
    // 4
    function func_return_closure() {
        return function() {
            return 'This is a closure';
        };
    }
    
    $output = ${!${''}=func_return_closure()}();
    
    echo '4: ';
    var_dump($output);
    

    输出:

    1: hello
    2: object(Thing)#1 (0) {
    }
    3: array(1) {
      [0]=>
      string(5) "hello"
    }
    4: string(17) "This is a closure"
    
        2
  •  2
  •   Kendall Hopkins    16 年前

    ${0} 而不是 ${''}

    以下陈述,

    line1;
    $output = line2;
    

    对于每个可能的情况,都与下面的语句相同。

    $output = (line1)&&0?:(line2);
    

    我的解决方案:

    <?php
    
    error_reporting(E_ALL | E_STRICT);
    
    // 1
    function func_return_array() { return array(0 => 'hello'); }
    $key = 0;
    
    $output = (${0}=func_return_array())&&0?:${0}[$key];
    
    echo '1: ' . $output . "\n";
    
    
    // 2
    class Thing {}
    $class_base = 'Thi'; $class_suffix = 'ng';
    
    $output = (${0}=$class_base.$class_suffix)&&0?:new ${0};
    
    echo '2: ';
    var_dump($output);
    
    
    // 3
    $func_base = 'func_'; $func_suffix = 'return_array';
    
    $output = (${0}=$func_base.$func_suffix)&&0?:${0}();
    
    echo '3: ';
    var_dump($output);
    
    
    // 4
    function func_return_closure() {
        return function() {
            return 'This is a closure';
        };
    }
    
    $output = call_user_func(func_return_closure()); //more straight forward
    //$output = (${0}=func_return_closure())&&0?:${0}();
    echo '4: ';
    var_dump($output);
    
    ?>