PHP namespaces, traits, and generators

Source: Internet
Author: User
Tags aliases php language traits
This paper mainly introduces the new features of PHP namespace, character and generator related data, mainly involved in PHP trait (traits) and generator (generator) Aspects of the content, for PHP trait (traits) and generator (generator) Interested students can refer to a bit. Hope to help everyone.

1. Namespaces

What is a namespace?

1). Namespaces are introduced in PHP 5.3, similar to the functionality of a folder. For example, the request and response in the Symfony framework are located under the Symfony namespace.

2). The namespace should always be on the line below the <?php label.

3). PHP file namespace and the operating system of the physical file system is different, this is a virtual concept, there is no need and the file system directory structure of the full correspondence. Nonetheless, the vast majority of PHP components automatically load standards for compatibility with widely used PSR4, which are placed into subdirectories of the file system.

4). The namespace is just a notation for the PHP language, and the PHP interpreter adds the notation as a prefix to the names of classes, interfaces, functions, and constants.

Why do I need namespaces?

1). Namespaces allow programs to run like sandbox, and can be used with code written by other developers. Ensure that your code and projects can be used with the third-party dependencies of your project.

declaring namespaces

1). Top-level namespaces are often used to set top-level vendor names. 2). The namespace of the vendor must be globally unique, and the child namespace is less important, but helps to organize the code for the project.

Import and aliases

1). Starting with PHP5.3, you can import PHP classes, interfaces, and other namespaces and create aliases for them. Starting with PHP5.6, you can import PHP functions and constants and create aliases for them.

2). You do not need to add a symbol at the beginning when importing code using the Use keyword, because PHP assumes that you are importing a fully qualified namespace. The Use keyword must appear in the global scope and cannot appear in a class or function, because the keyword is used at compile time, but the USE keyword can be used after the namespace declaration statement to import code for other namespaces.

Starting with PHP5.6 we can import functions and constants.

<?phpuse func namespace\functionname;functionname ();

You can also import constants,

Use constant Namespace\cons_name;echo cons_name;

The aliases of functions and constants are the same as the way the class names are created.

Best practices

1). PHP allows you to define multiple namespaces in a single PHP file. But doing so is confusing and violates a good practice of a file class. 2). When referencing the global namespace code in a namespace, prefix is required to tell PHP to look for the class in the global, such as the PHP native exception class.

Auto Load

1). The namespace lays a solid foundation for the PSR4 Autoloader developed by Php-fig.

2. Using the interface

1). It's like I can choose to drive a different car. Because they all have the steering wheel, the throttle and the brakes, and the fuel is gasoline.

3. Traits

1). Shapes are partial implementations of a class (constants, properties, and methods) that can be mixed into one or more existing PHP classes, with two functions that indicate what classes can do (like interfaces) and provide modular practices (similar classes).

2). Traits allow two unrelated classes to use the same properties and methods.

3). The PHP interpreter will copy and paste the traits into the definition body of the class.

4. Creating generators

1) Use the yield keyword one or more times in a normal function, not return a value, only generate a value, this function is a generator. For example:

<?phpfunction Mygenerator () {yield ' value1 '; yield ' value2 ';}

When invoking the generator function, PHP returns an object belonging to the generator class, which can use the foreach () function iteration, where PHP will require an instance of this object to compute and provide the next iteration value, and the elegance of the generator is that after each output value, The internal state of the generator switches between pausing and resuming until the end of the defined body is reached or an empty return is encountered, for example:

<?phpforeach (Mygenerator () as $yieldedValue) {echo $yieldedValue, php_eol;}

The above example will output

Value1value2

2). How does the generator save memory? Generate a range of numeric values (in the wrong way)

function Makerange ($length) {$dataset = []; for ($i =0; $i < $length; $i + +) {$dataset [] = $i;} return $dataset;} $customRange = Makerange (1000000), foreach ($customeRange as $i) {echo $i, php_eol;}

Create an array with a large number of integers in advance, and then look at examples of using generators.

function Makerange ($length) {for ($i = 0; $i < $length; $i + +) {yield $i;}} foreach (Makerange (1000000) as $i) {echo $i, php_eol;}

Iterators are a big player in real-world functions such as iterating over a 4GB-sized file.

function GetRows ($file) {$handle = fopen ($file, ' RB '), if ($handle = = = False) {throw new Exception ();} The//feof () function detects if it arrives The end of the file while (feof ($handle) = = = False) {//fgetcsv () reads a CSV file one line yield fgetcsv ($handle) at a time, fclose ($handle)}foreach (getRows (' Data.csv ') as $row) {print_r ($row);}

3). The generator does not add new functionality to PHP, it needs to implement fast forward, rewind, and find in the dataset, it is best to write your own class to implement the iterator interface, or use a native iterator in the PHP standard library.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.