Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Examples of object overloading techniques and methods in PHP5

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "PHP5 object overloading technology and method reloading examples". In daily operation, I believe that many people have doubts about PHP5 object overloading technology and method reloading examples. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "PHP5 object overloading technology and method reloading examples". Next, please follow the editor to study!

1. What is object overloading?

When talking about object overloading in PHP, we distinguish between two types:

◆ method overload

◆ property overload

In the case of method overloading, we define a magic method _ _ call () that implements a general call to an undefined method in the corresponding class. This general method is called only if you want to access methods that are not defined in the class. In the absence of method overloading, the following example causes PHP to display a fatal error message: Call to undefined method ThisWillFail::bar () in/some/directory/example.php on line 9 and abort the execution of the program:

Php class ThisWillFail {public function foo () {return "Hello World!";}} $class = new ThisWillFail; $class- > bar ();? >

With the help of method overloading, the code can capture this call and handle it gracefully. Property overloading is similar to method overloading. In this case, the class redirects read / write operations (also known as proxies) to the class's properties, which are not explicitly defined in the class. The special methods here are _ _ set () and _ _ get (). Depending on the error reporting level, PHP translators usually either issue a notification or delay and potentially define the variable when accessing an undefined property.

If you use property overloading, the translator can call _ _ set () when setting an undefined property and _ _ get () when accessing an undefined property value. To sum up, the software development time can be greatly shortened when using a dynamic language such as PHP by using overloading technology.

2. Examples of persistent storage

The following code implements the persistent storage class mentioned above with less than 50 lines of PHP code by using property overloading techniques. The term persistable means that a class can describe an element from a data structure and keep it synchronized with the bottom storage system. The explanation in coding is that external code can use classes to select a row from a database table.

In this way, while the program is running, you can directly access the properties of the class to manipulate the elements in the line (read / fetch). At the end of the script, PHP will be responsible for sending the updated row data back to the database. Careful study of the following code will help you understand what attribute overloading is.

DB package < / a > require_once" DB.php "; class Persistable {private $data = array (); private $table =" users "; public function _ construct ($user) {$this- > dbh = DB::Connect (" mysql://user:password@localhost/database "); $query =" SELECT id, name, email, country FROM ". $this- > table. "WHERE name =?"; $this- > data = $this- > dbh- > getRow ($query, array ($user), DB_FETCHMODE_ASSOC);} public function _ get ($member) {if ($this- > data [$member]) {return $this- > data [$member];}} public function _ set ($member, $value) {/ / dataset ID is read-only if ($member = "id") {return } if (isset ($this- > data [$member])) {$this- > data [$member] = $value;}} public function _ destruct () {$query = "UPDATE". $this- > table. "SET name =?, email =?, country =? WHERE id =?"; $this- > dbh- > query ($query, $this- > name, $this- > email, $this- > country, $this- > id);} $class = new Persistable ("Martin Jansen"); $class- > name = "John Doe"; $class- > country = "United States"; $class- > email = "john@example.com";? >

The problem you encounter may be _ _ construct (), a new constructor method introduced in PHP 5. In the PHP 4 era, constructors always matched their class names. This is no longer the case in PHP 5. You don't need to know much about constructor methods, except that you can call it to create an instance of a class; and notice that a parameter is used here-to execute a database based on this parameter. This constructor assigns the query result to the class attribute $data.

Next, the program defines two special methods, _ _ get () and _ _ set (). You should already be familiar with them: _ _ get () is used to read undefined attribute values, and _ _ set () is used to modify undefined attribute values.

This means that whenever an undefined property is read / written from a persistent storage class, these special methods are responsible for managing the information in the attribute array variable $data, rather than directly changing the class's properties (remember: the variable $data contains a row from the database!).

One of the * * methods in the class is the opposite of _ _ construct ()-the destructor _ _ destruct (). PHP invokes the destructor during the script shutdown phase, typically at the end of PHP script execution. The destructor writes the information from the $data attribute back to the database. This is exactly what the previous synchronization term means.

You may have noticed that the code here uses PEAR's database abstraction layer package (database abstraction layer package). In fact, it does not matter, through other ways to communicate with the database can also explain the theme of this article.

If you look closely, you will find that the description of this persistent storage class is relatively simple. Only one database table is involved in the example, without considering more complex data models, such as the use of LEFT JOIN and other complex database manipulation techniques. However, you do not have to be subject to this constraint, with the help of property overloading, you can use your own ideal database model. With a little code, you can use complex database features in this persistent storage class.

There is also a small problem-no error handling mechanism is introduced when the query fails in the destructor. It is the nature of the destructor that makes it impossible to display the corresponding error message in this case, because building the HTML flag is often finished before the PHP invokes the destructor.

To solve this problem, you can rename _ _ destruct () to a name like saveData () and execute this method manually somewhere in the calling script. This doesn't change the concept of persistent storage for classes; it's just writing a few more lines of code. Alternatively, you can also use the function error_log () in the destructor to record error messages in system-wide error log files. This is how property overloading works. Let's talk about method overloading.

Third, examples of method overloading

1. Dynamic Getter/Setter method

The following code implements the "dynamic" getter/setter method to control the class with the help of method overloading. Let's analyze it with the source code:

$property)) {return $this- > $property } if ($prefix = = "set") {$this- > $property = $arguments [0];}} $class = new DynamicGetterSetter; echo "Name:". $class- > getName (). "\ n"; echo "Favourite Starbucks flavour:" $class- > getStarbucksDrink (). "\ n\ n"; $class- > setName ("John Doe"); $class- > setStarbucksDrink ("Classic Coffee"); echo "Name:". $class- > getName (). "\ n"; echo "Favourite Starbucks flavour:" $class- > getStarbucksDrink (). "\ n\ n";? >

Obviously, the two properties $name and $starbucksdrink here are private, meaning they cannot be accessed from outside the class. In object-oriented programming, it is common to implement public getter/setter methods to access or modify the values of non-public properties. Achieving these things is tedious and takes a lot of time and effort.

This problem can be easily solved by means of overloading. Instead of implementing the getter/setter method for each property, only a generic _ _ call () method is implemented above. This means that when you call an undefined getter/setter method such as setName () or getStarbucksdrink (), PHP does not produce a fatal error and aborts, but executes (or proxies to) the magic _ _ call () method. Here are some brief introductions. Let's make an in-depth analysis of _ _ call ().

two。 Detailed analysis of _ _ call () method

The * parameters of _ _ call () are the original and undetermined method (such as setName), and the second parameter is an one-dimensional array of a numeric index that contains all the parameters of the original method. Calling an undefined method with two parameters ("Martin" and 42) produces the following array:

$class- > thisMethodDoesNotExist ("Martin", 42); / second parameter Array of guide _ _ call () ([0] = > Martin [1] = > 42)

Inside the method _ _ call (), if the original method starts with get or set, some calculation is performed to determine whether the code is calling a getter/setter method. Furthermore, this method further parses another part of the method name (excluding the first three characters), because the latter part of the string represents the name of the attribute referenced by the getter/setter.

If a getter/setter is indicated in the method name, the method either returns the corresponding property value or sets the value of the * * parameters of the original method. If not, it does not do anything and continues to execute the program as if nothing had happened.

3. Achieve the goal

In essence, corresponding to arbitrary attributes, there is a method that allows code to call arbitrary getter/setter methods dynamically, and this algorithm exists. This is convenient when developing a program prototype in a short period of time: instead of spending a lot of time implementing getters/setters, developers can focus on modeling API and ensuring that the application is fundamentally correct. Incorporating the _ _ call () method into an abstract class may even enable you to achieve code reuse in future PHP engineering development!

4. Beyond the deficiency

There are advantages and disadvantages. The above approach also has several drawbacks: larger projects can use tools such as phpDocumentor to track API structures. With the dynamic methods described above, all getter/setter methods certainly do not appear in the automatically generated document, which does not need to be explained.

Another drawback is that code outside the class can access every private property within the class. When using real getter/setter methods, it is possible to distinguish between private properties that can be accessed by external code and "real" private properties that are not visible outside the class-because we have method overloads and virtual getter and setter methods are available.

At this point, the study of "examples of object overloading techniques and methods of PHP5" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report