Linked list data structure in PHP?
I'm wondering how can I use pointers in PHP. I've experience in C with pointers and creating data structures like lists, linked lists (chains) and similar, and now I want to do these in PHP. The first thing I've read about references are that they ARE NOT pointers :)
I'm interested if PHP can do structs? *sigh* Why all PHP learning books write only about making SQL queries and writing HTML :( |
In PHP4 or 5 you would set up a class, which would give you an object. You can use the object like a struct, if that is what you want to do. You also can do indirection with PHP. The syntax is not nearly so elegant as C pointer syntax, but it is possible.
|
In PHP 5, everything is now passed-by-reference, which is good, because it makes making data structures simpler. In PHP4, when you would pass an object to a function, it only passed a value (a copy, essentially). So, any where you wanted to pass an object by reference, you had to use an & (ampersand), but, with PHP, it becamse pretty easy to accidently make a copy instead. The main point is, if you plan on supporting PHP4, it'll take a bit more work and be a bit uglier. PHP5 references are not pointers per se, no, but they are used in the way you expect. Anyways, here is part of a simple linked list in PHP5.
Code:
class LinkedList { Quote:
|
Thank you!
I'd better sit on these classes. |
In the strict sense of the definition a reference is not a pointer, however it is a way of referring to another variable and so from a data structures view point it performs the task of a pointer. Many years ago I wrote some code in PHP illustrating how the basic data structures work, so it's possible, and yes I used the class approach suggested by the previous posters.
|
Just for clearance, I believe that line of your code:
Code:
$this->head = $this->tail = $data; Code:
$this->head = $this->tail = $node; Yahoo! My first PHP stack: Code:
<?php |
That looks correct to me, although I've not tried to run it! What I would say is that the constructor you are using is PHP4 syntax, in PHP5 they changed it to be __construct(), if you have access to PHP5 I'd use that because it has much better OO support.
|
All times are GMT -5. The time now is 04:22 AM. |