Use the object as an array in PHP

Source: Internet
Author: User
Tags access properties
We understand that in JavaScript, the properties and methods of an object can be accessed using the pattern of an array. But it's usually impossible.

Why do you do this? This is because, in this way, it is easier to manipulate objects, and we can define a class. Instead of defining a key value array. Naturally, if we have other options, one of the simplest is to force conversions to an array. However, this will lose the way the original object.

However, arrayobject in SPL can help us to access properties in array mode. But the method still cannot be realized.

The Arrayobject class structure is as follows (some methods are added at php5,1 or php5.2):

arrayobject implements Iteratoraggregate, Traversable, Arrayaccess, Serializable, countable {/* constant */const integer std_prop_list = 1; Const integer ARRAY_AS_PROPS = 2;/* Method */__construct ( [Mixed $input [, int $flags [, String $iterator _class]]) void append (mixed $value) void asort (void) int count (void) array exchangearray (mixed $input) array getarraycopy ( void) int getflags (void) arrayiterator getiterator (void) int getiteratorclass (void) void ksort (void) void natcases Ort (void) void natsort (void) bool Offsetexists (mixed $index) mixed offsetget (mixed $index) void Offsetset (mixed $index, mixed $newval) void Offsetunset (mixed $index) public void serialize (void) void setflags (int $flags) void SE Titeratorclass (string $iterator _class) void Uasort (callback $cmp _function) void Uksort (callback $cmp _function) publi c void Unserialize (String $serialized)} 

Where: Why do we have direct access to $obj->name with $obj [' name ']? There are three main methods in the above method:

Offsetget support $obj[' name ') Read the way

Offsetset support for $obj[' name ') writing method

But foreach is the default implementation of this class for Arrayaccess's function, current, and so on.

Look at an example code:

Class Test extends Arrayobject{public $name;p rivate $age = 21;public function Show () {Print_r (Get_object_vars ($this));}} Class Test1{public $name;p rivate $age = 21;public function Show () {Print_r (Get_object_vars ($this));}} $obj =new Test ()//Read and write properties using array $obj[' name ']= ' Hello '; $obj [' Nick ']= ' Mockarray '; echo $obj [' Nick '], ' </br> '; var_ Dump ($obj [' Show ']);//Detect whether the method can be accessed: Print_r ($obj);//Output Object $obj->show ();//Call Method $arr= (array) $obj; Forces an array to be converted. Print_r ($arr);//$arr->show (); This line will be faulted because the original method is all lost. $obj 1=new test1 (); Create a Normal object $arr1= (array) $obj 1; Forces an array to be converted. Print_r ($arr 1); Privacy Full Exposure

This code will output:

Mockarray</br>null
Test Object
(
[name] = = Hello
[Nick] = Mockarray
)
Array
(
[name] = = Hello
[Nick] = Mockarray
)
Array
(
[name] = = Hello
[Nick] = Mockarray
)
Array
(
[Name] + =
[test1 Age] = 21
)

As you can see, you can use array mode to access the property, but you cannot access the method (member function).

After casting, it is an array object with no member function.

Of course Offsetget Offsetset These two methods, can also be further rewritten according to our needs. Why? Because, if there are some very perverted needs, certainly useful. For example, we are going to wrap three arrays in a reference way into an object, which is accessed as an array. At this point, you need to rewrite these two functions. Of course, you should also rewrite the corresponding function in the Arrayaccess interface.

Again, all that is accessible is the public attribute. If it is private, it cannot be accessed. The same is true even if you are forced to convert an array. But if you don't inherit arrayobject, it's different. Such a class, once coerced into an array, is exposed to its privacy (the private attribute).

However, we can see that the original property name is not preserved after the private attribute has been converted to an array. Instead, it uses the form of a non-printable character + class name + non-printable character + attribute name. This non-printable character ASCII is how much is not checked, you have to be interested to check!

  • 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.