PHP 的隐藏功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/61401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:20:54  来源:igfitidea点击:

Hidden Features of PHP?

phphidden-features

提问by George Mauer

I know this sounds like a point-whoring question but let me explain where I'm coming from.

我知道这听起来像是一个吹毛求疵的问题,但让我解释一下我来自哪里。

Out of college I got a job at a PHP shop. I worked there for a year and a half and thought that I had learned all there was to learn about programming.

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

Then I got a job as a one-man internal development shop at a sizable corporation where all the work was in C#. In my commitment to the position I started reading a ton of blogs and books and quickly realized how wrong I was to think I knew everything. I learned about unit testing, dependency injection and decorator patterns, the design principle of loose coupling, the composition over inheritance debate, and so on and on and on - I am still very much absorbing it all. Needless to say my programming style has changed entirely in the last year.

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

Now I find myself picking up a php project doing some coding for a friend's start-up and I feel completely constrained as opposed to programming in C#. It really bothers me that all variables at a class scope have to be referred to by appending '$this->' . It annoys me that none of the IDEs that I've tried have very good intellisense and that my SimpleTest unit tests methods have to start with the word 'test'. It drives me crazy that dynamic typing keeps me from specifying implicitly which parameter type a method expects, and that you have to write a switch statement to do method overloads. I can't stand that you can't have nested namespaces and have to use the :: operator to call the base class's constructor.

现在我发现自己拿起一个 php 项目,为朋友的初创公司做一些编码,与使用 C# 编程相比,我感到完全受限。必须通过附加 '$this->' 来引用类范围内的所有变量,这真的让我感到困扰。令我烦恼的是,我尝试过的所有 IDE 都没有非常好的智能感知,而且我的 SimpleTest 单元测试方法必须以“测试”这个词开头。动态类型使我无法隐式指定方法期望的参数类型,并且您必须编写 switch 语句来执行方法重载,这让我发疯。我不能忍受你不能有嵌套的命名空间并且必须使用 :: 运算符来调用基类的构造函数。

Now I have no intention of starting a PHP vs C# debate, rather what I mean to say is that I'm sure there are some PHP features that I either don't know about or know about yet fail to use properly. I am set in my C# universe and having trouble seeing outside the glass bowl.

现在我无意开始 PHP 与 C# 的辩论,而是我的意思是我确定有一些 PHP 功能我不知道或知道但未能正确使用。我被设置在我的 C# 世界中并且无法看到玻璃碗外面。

So I'm asking, what are your favorite features of PHP? What are things you can do in it that you can't or are more difficult in the .Net languages?

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

回答by Kyle Cronin

Documentation. The documentationgets my vote. I haven't encountered a more thorough online documentation for a programming language - everything else I have to piece together from various websites and man pages.

文档。该文件得到我的投票。我还没有遇到过关于编程语言的更详尽的在线文档 - 我必须从各种网站和手册页拼凑起来的所有其他内容。

回答by user8134

Arrays. Judging from the answers to this question I don't think people fully appreciate just how easy and useful Arrays in PHP are. PHP Arrays act as lists, maps, stacks and generic data structures all at the same time. Arrays are implemented in the language core and are used all over the place which results in good CPU cache locality. Perl and Python both use separate language constructs for lists and maps resulting in more copying and potentially confusing transformations.

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

回答by Allain Lalonde

Stream Handlersallow you to extend the "FileSystem" with logic that as far as I know is quite difficult to do in most other languages.

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

For example with the MS-Excel Stream handleryou can create a MS Excel file in the following way:

例如,使用MS-Excel Stream 处理程序,您可以通过以下方式创建 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);

回答by Allain Lalonde

Magic Methodsare fall-through methods that get called whenever you invoke a method that doesn't exist or assign or read a property that doesn't exist, among other things.

魔术方法是贯穿方法,每当您调用不存在的方法或分配或读取不存在的属性等时,都会调用这些方法。

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);
}

A C++ developer here might notice, that PHP allows overloading some operators, e.g. ()or (string). Actually PHP allows overloading even more, for example the []operator (ArrayAccess), the foreachlanguage construct (Iteratorand IteratorAggregate) and the countfunction (Countable).

这里的 C++ 开发人员可能会注意到,PHP 允许重载某些运算符,例如()(string)。实际上 PHP 允许更多的重载,例如[]运算符(ArrayAccess)、foreach语言结构(IteratorIteratorAggregate)和count函数(Countable)。

回答by Dean Rather

The standard classis a neat container. I only learned about it recently.

标准类是一个整洁的容器。我最近才知道。

Instead of using an array to hold serveral attributes

而不是使用数组来保存多个属性

$person = array();
$person['name'] = 'bob';
$person['age'] = 5;

You can use a standard class

您可以使用标准类

$person = new stdClass();
$person->name = 'bob';
$person->age = 5;

This is particularly helpful when accessing these variables in a string

这在访问字符串中的这些变量时特别有用

$string = $person['name'] . ' is ' . $person['age'] . ' years old.';
// vs
$string = "$person->name is $person->age years old.";

回答by Philippe Gerber

Include files can have a return valueyou can assign to a variable.

包含文件可以有一个可以分配给变量的返回值

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

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

回答by Micha? Tatarynowicz

You can take advantage of the fact that the oroperator has lower precedence than =to do this:

您可以利用or运算符的优先级低于=执行此操作的事实:

$page = (int) @$_GET['page'] 
  or $page = 1;

If the value of the first assignment evaluates to true, the second assignment is ignored. Another example:

如果第一个赋值的值为true,则忽略第二个赋值。另一个例子:

$record = get_record($id) 
  or throw new Exception("...");

回答by Willem

__autoload()(class-) files aided by set_include_path().

__autoload()(class-) 文件由set_include_path().

In PHP5 it is now unnecessary to specify long lists of "include_once" statements when doing decent OOP.

在 PHP5 中,在执行体面的 OOP 时,现在没有必要指定一长串“include_once”语句。

Just define a small set of directory in which class-library files are sanely structured, and set the auto include path:

只需定义一小组目录,其中类库文件的结构合理,并设置自动包含路径:

set_include_path(get_include_path() . PATH_SEPARATOR . '../libs/');`

Now the __autoload()routine:

现在的__autoload()日常:

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');
}

Now PHP will automagically include the needed files on-demand, conserving parsing time and memory.

现在 PHP 将自动按需包含所需的文件,从而节省解析时间和内存。

回答by Jrgns

Variable variables and functionswithout a doubt!

变量变量和函数毫无疑问!

$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!

The same concept applies to object parameters ($some_object->$some_variable);

相同的概念适用于对象参数 ($some_object->$some_variable);

Very, very nice. Make's coding with loops and patterns very easy, and it's faster and more under control than eval (Thanx @Ross & @Joshi Spawnbrood!).t

非常非常棒。使用循环和模式进行编码非常容易,而且它比 eval 更快、更容易控制(感谢 @Ross 和 @Joshi Spawnbrood!)。

回答by Chris Ridenour

Easiness. The greatest feature is how easy it is for new developers to sit down and write "working" scripts and understand the code.

轻松。最大的特点是新开发人员坐下来编写“工作”脚本和理解代码是多么容易。

The worst feature is how easy it is for new developers to sit down and write "working" scripts and think they understand the code.

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

The openness of the communitysurrounding PHP and the massive amounts of PHP projects available as open-source is a lot less intimidating for someone entering the development world and like you, can be a stepping stone into more mature languages.

围绕 PHP的社区开放性以及作为开源提供的大量 PHP 项目对于进入开发世界的人来说并不那么令人生畏,并且像您一样可以成为进入更成熟语言的垫脚石。

I won't debate the technical things as many before me have but if you look at PHP as a community rather than a web language, a community that clearly embraced you when you started developing, the benefits really speak for themselves.

我不会像之前的许多人那样争论技术问题,但是如果您将 PHP 视为一个社区而不是 Web 语言,一个在您开始开发时就清楚地拥抱您的社区,那么好处不言而喻。