Back to home

PHP Constructors main image

PHP Constructors

This is a overly simplified application of a how to use constructors in PHP with a very limited LinkedList class that omits most common methods.

The main point of this post is to show how to create classes that in turn can be used to create instances using __construct.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class LinkedList { public $size = 0; public $head; function __construct($head = null) { $this->head = $head; if ($head != null) { $this->size = 1; } else { $this->size = 0; } } public function insertFirst($n) { if ($this->head != null) { $tmp = $this->head; $this->head = $n; $n->setNext($tmp); } else { $this->head = $n; } $this->size++; } public function getFirst() { return $this->head; } } class Node { private $data; private $next; function __construct($data = null) { $this->data = $data; } public function getData() { return $this->data; } public function setData($data) { $this->data = $data; } public function getNext() { return $this->next; } public function setNext($next) { $this->next = $next; } } $n1 = new Node(1); $n2 = new Node(2); $ll = new LinkedList($n1); $ll->insertFirst($n2); $ll->getFirst(); // returns $n2

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.