I learning a bit of OO PHP but the docs I came across showed a couple of methods of the following examples. I am confused as to why both work, and which should be used exclusively.
I know that #1 is not OOP but I was still curious about the second method of echo, and if it should be used or not.
-
Both of the
echo
's below print "Lansana", but one initializes$name
before the echo whereas the other initializes it after (or during) the echo.<?php $name = "Lansana"; echo $name; echo $name = "Lansana"; ?>
-
Notice how there is a public property
$name
with no value in the first example, and no public property in the second, yet both still work the same.class Pets { public $name; public function __construct($name) { $this->name = $name; } } $dog = new Pets("Buddy"); echo $dog->name;
class Pets { public function __construct($name) { $this->name = $name; } } $dog = new Pets("Buddy"); echo $dog->name;
What is the preferred method in #1 and #2, and why? I don't know why the docs showed the first class method because I don't see the need for a public property there, but then again what do I know.