PHP的隐藏特性?

PHP的隐藏特性?,php,hidden-features,Php,Hidden Features,我知道这听起来像是一个问题,但让我解释一下我是从哪里来的 大学毕业后,我在一家PHP商店找到了一份工作。我在那里工作了一年半,认为我已经学会了编程的所有知识 然后我在一家大型公司找到了一份一人内部开发的工作,所有的工作都在C#。在我对这个职位的承诺中,我开始阅读大量的博客和书籍,并很快意识到我认为自己什么都知道是错的。我学习了单元测试、依赖注入和装饰器模式、松耦合的设计原则、组合而非继承的争论等等——我仍然非常专注于此。不用说,我的编程风格在去年已经完全改变了 现在,我发现自己正在为一位朋友的初

我知道这听起来像是一个问题,但让我解释一下我是从哪里来的

大学毕业后,我在一家PHP商店找到了一份工作。我在那里工作了一年半,认为我已经学会了编程的所有知识

然后我在一家大型公司找到了一份一人内部开发的工作,所有的工作都在C#。在我对这个职位的承诺中,我开始阅读大量的博客和书籍,并很快意识到我认为自己什么都知道是错的。我学习了单元测试、依赖注入和装饰器模式、松耦合的设计原则、组合而非继承的争论等等——我仍然非常专注于此。不用说,我的编程风格在去年已经完全改变了

现在,我发现自己正在为一位朋友的初创公司编写一个php项目,与用C#编程相比,我感到完全受限制。一个类作用域中的所有变量都必须通过附加“$this->”来引用,这让我非常困扰。我尝试过的IDE没有一个具有很好的智能感,我的SimpleTest单元测试方法必须以“test”这个词开头,这让我很恼火。动态类型使我无法隐式指定方法所需的参数类型,并且必须编写switch语句来执行方法重载,这让我抓狂。我不能忍受不能有嵌套的名称空间,而必须使用::运算符来调用基类的构造函数

现在,我无意开始一场PHP与C的辩论,我想说的是,我确信有一些PHP特性我不知道或不知道,但无法正确使用。我被设定在我的C#宇宙中,在玻璃碗外面看不见东西


所以我想问,你最喜欢的PHP特性是什么?在.Net语言中,您可以做哪些您不能做或更难做的事情?

这里有一件事,我喜欢在未提供的函数参数上设置默认值要容易得多:

function MyMethod($VarICareAbout, $VarIDontCareAbout = 'yippie') { }
是直通式方法,在调用不存在的方法或分配或读取不存在的属性时,会调用这些方法

interface AllMagicMethods {
    // accessing undefined or invisible (e.g. private) properties
    public function __get($fieldName);
    public function __set($fieldName, $value);
    public function __isset($fieldName);
    public function __unset($fieldName);

    // calling undefined or invisible (e.g. private) methods
    public function __call($funcName, $args);
    public static function __callStatic($funcName, $args); // as of PHP 5.3

    // on serialize() / unserialize()
    public function __sleep();
    public function __wakeup();

    // conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)
    public function __toString();

    // calling the object like a function (e.g. $obj($arg, $arg2))
    public function __invoke($arguments, $...);

    // called on var_export()
    public static function __set_state($array);
}

这里的C++开发人员可能会注意到PHP允许重载一些运算符,例如<代码>()<>代码>或<代码>(string)< /C>。实际上,PHP甚至允许重载,例如

[]
操作符(),
foreach
语言构造(and)和
count
函数()。

流处理程序允许您使用逻辑扩展“文件系统”,据我所知,这在大多数其他语言中是很难做到的

例如,您可以使用以下方式创建MS Excel文件:

$fp = fopen("xlsfile://tmp/test.xls", "wb");
if (!is_resource($fp)) { 
    die("Cannot open excel file");
}

$data= array(
    array("Name" => "Bob Loblaw", "Age" => 50),  
    array("Name" => "Popo Jijo", "Age" => 75),  
    array("Name" => "Tiny Tim", "Age" => 90)
); 

fwrite($fp, serialize($data));
fclose($fp);

文档。总统得到了我的选票。我还没有遇到过更全面的编程语言在线文档——我必须从各种网站和手册页拼凑的所有其他内容。

数组操作。

大量用于处理和操纵阵列的工具。它可能不是PHP独有的,但我从来没有使用过一种语言使它如此简单。

支持PHP的Web空间通常比使用(asp.net)的东西便宜。
您可以称之为功能;-)

变量和函数毫无疑问

$foo = 'bar';
$bar = 'foobar';
echo $$foo;    //This outputs foobar

function bar() {
    echo 'Hello world!';
}

function foobar() {
    echo 'What a wonderful world!';
}
$foo();    //This outputs Hello world!
$$foo();    //This outputs What a wonderful world!
同样的概念也适用于对象参数($some_object->$some_variable)


非常非常好。Make使用循环和模式进行编码非常简单,而且比eval(Thanx@Ross和Joshi sprownfound!)更快、更可控。t

数组。从这个问题的答案来看,我认为人们并不完全理解PHP中的数组有多么简单和有用。PHP数组同时充当列表、映射、堆栈和通用数据结构。数组是在语言核心中实现的,并在所有地方使用,从而产生良好的CPU缓存局部性。Perl和Python都对列表和映射使用单独的语言构造,这会导致更多的复制和潜在的混乱转换。

易用性。最大的特点是,对于新开发人员来说,坐下来编写“工作”脚本并理解代码是多么容易

最糟糕的特性是,对于新开发人员来说,坐下来编写“工作”脚本并认为他们理解代码是多么容易

社区的开放性围绕着PHP和大量可用的开源PHP项目,对于进入开发世界的人来说,没有那么可怕,就像你一样,可以成为进入更成熟语言的垫脚石


我不会像前面的许多人那样讨论技术问题,但是如果你把PHP看作一个社区,而不是一种web语言,一个在你开始开发时就明确接受你的社区,其好处是不言而喻的。

PHP的一个不太为人所知的特性是,将关联数组解压到本地命名空间中的函数。这可能适用于自动全局中止,但对于模板化非常有用:

function render_template($template_name, $context, $as_string=false)
{
    extract($context);
    if ($as_string)
        ob_start();
    include TEMPLATE_DIR . '/' . $template_name;
    if ($as_string)
        return ob_get_clean();
}

现在你可以使用
render_模板('index.html',array('foo'=>'bar'))
并且只有
$foo
“bar”
出现在模板中。

我有点像你,我编写PHP已经超过8年了。大约一年前,我不得不参加.NET/C#课程,我非常喜欢C#语言(讨厌ASP.NET),但它使我成为了一名更好的PHP开发人员

PHP作为一种语言是非常糟糕的,但是,我非常快地使用它,LAMP堆栈非常棒。最终产品远远超过了各部分的总和

也就是说,在回答你的问题时:

我喜欢SPL,C#中的收集课程是我一开始就喜欢的。现在我可以吃蛋糕了
set_include_path(get_include_path() . PATH_SEPARATOR . '../libs/');`
function __autoload($classname) {
    // every class is stored in a file "libs/classname.class.php"

    // note: temporary alter error_reporting to prevent WARNINGS
    // Do not suppress errors with a @ - syntax errors will fail silently!

    include_once($classname . '.class.php');
}
<?php $flag and print "Blah" ?>
$person = array();
$person['name'] = 'bob';
$person['age'] = 5;
$person = new stdClass();
$person->name = 'bob';
$person->age = 5;
$string = $person['name'] . ' is ' . $person['age'] . ' years old.';
// vs
$string = "$person->name is $person->age years old.";
$page = (int) @$_GET['page'] 
  or $page = 1;
$record = get_record($id) 
  or throw new Exception("...");
if (preg_match("/cat/","one cat")) {
   // do something
}
import java.util.regex.*;
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat")
if (m.find()) {
  // do something
}
function myFunc($param1, $param2 = MY_CONST)
{
//code...
}
$str = 'hell o World';
echo $str; //outputs: "hell o World"

$str[0] = 'H';
echo $str; //outputs: "Hell o World"

$str[4] = null;
echo $str; //outputs: "Hello World"
class style
{
  ....
  function set_bg_colour($c)
  {
    $this->{'background-color'} = $c;
  }
}
$fp = fopen('http://example.com');
$str = file_get_contents('http://example.com/file');
$imageInfo = getimagesize('ftp://user:password@ftp.example.com/image/name.jpg');
/*
    die('You shall not pass!');
//*/


//*
    die('You shall not pass!');
//*/
<?php
function foo($arg1)
{
    static $cache;

    if( !isset($cache[md5($arg1)]) )
    {
        // Do the work here
        $cache[md5($arg1)] = $results;
    }

    return $cache[md5($arg1)];
}
?>
// swap values. any number of vars works, obviously  
list($a, $b) = array($b, $a);

// nested list() calls "fill" variables from multidim arrays:  
$arr = array(  
  array('aaaa', 'bbb'),  
  array('cc', 'd')  
);  
list(list($a, $b), list($c, $d)) = $arr;  
echo "$a $b $c $d"; // -> aaaa bbb cc d  

// list() values to arrays  
while (list($arr1[], $arr2[], $arr3[]) = mysql_fetch_row($res)) { .. }  
// or get columns from a matrix  
foreach($data as $row) list($col_1[], $col_2[], $col_3[]) = $row;

// abusing the ternary operator to set other variables as a side effect:  
$foo = $condition ? 'Yes' . (($bar = 'right') && false) : 'No' . (($bar = 'left') && false);  
// boolean False cast to string for concatenation becomes an empty string ''.  
// you can also use list() but that's so boring ;-)  
list($foo, $bar) = $condition ? array('Yes', 'right') : array('No', 'left');
// the strings' "Complex syntax" allows for *weird* stuff.  
// given $i = 3, if $custom is true, set $foo to $P['size3'], else to $C['size3']:  
$foo = ${$custom?'P':'C'}['size'.$i];  
$foo = $custom?$P['size'.$i]:$C['size'.$i]; // does the same, but it's too long ;-)  
// similarly, splitting an array $all_rows into two arrays $data0 and $data1 based  
// on some field 'active' in the sub-arrays:  
foreach ($all_rows as $row) ${'data'.($row['active']?1:0)}[] = $row;

// slight adaption from another answer here, I had to try out what else you could  
// abuse as variable names.. turns out, way too much...  
$string = 'f.> <!-? o+';  
${$string} = 'asdfasf';  
echo ${$string}; // -> 'asdfasf'  
echo $GLOBALS['f.> <!-? o+']; // -> 'asdfasf'  
// (don't do this. srsly.)

${''} = 456;  
echo ${''}; // -> 456  
echo $GLOBALS['']; // -> 456  
// I have no idea.  
// just discovered you can comment the hell out of php:
$q/* snarf */=/* quux */$_GET/* foo */[/* bar */'q'/* bazz */]/* yadda */;
class foo {
  function __call($func, $args) {
    eval ($func);
  }
}

$x = new foo;
$x->{'foreach(range(1, 10) as $i) {echo $i."\n";}'}();
$foo = 'abcde';
$strlen = 'strlen';
echo "$foo is {$strlen($foo)} characters long."; // "abcde is 5 characters long."
// Set the normal defaults.
$control_defaults = array( 'type' => 'text', 'size' => 30 );

// ... many lines later ...

$control_5 = $control_defaults + array( 'name' => 'surname', 'size' => 40 );
// This is the same as:
// $control_5 = array( 'type' => 'text', 'name' => 'surname', 'size' => 40 );
for ($i=0; $i < $x; $i++) { 
    // code...
}
foreach (range(0, 12) as $number) {
    // ...
}
foreach (range(date("Y"), date("Y")+20) as $i)
{
print "\t<option value=\"{$i}\">{$i}</option>\n";
}
echo <<<EOM
  <div id="someblock">
    <img src="{$file}" />
  </div>
EOM;
<?php

function test() {

    $args = func_get_args();
    echo $args[2]; // will print 'd'
    echo $args[1]; // will print 3
}

test(1,3,'d',4);

?>
// config.php
return array(
    'db' => array(
        'host' => 'example.org',
        'user' => 'usr',
        // ...
    ),
    // ...
);

// index.php
$config = include 'config.php';
echo $config['db']['host']; // example.org