Last active
February 1, 2019 13:40
-
-
Save wesbasinger/ea43fc7703f7759eba6b46c9d5831c5c to your computer and use it in GitHub Desktop.
Member Variables in a Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Is there a difference between the two ways shown below of declaring a member variable in a class? | |
// If not, would there be a preference of one over the other? | |
class Foo { | |
public $bar = "baz"; | |
} | |
class Foo2 { | |
public function __construct() { | |
$this->bar = "baz"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Did you get my IM?
These are equivalent, until the value of baz gets complicated; What if baz was an object (database connection i.e. PDO)? Then you would could have a default value of NULL, create the extra object outside of FOO or FOO2, and then pass it in and set it in the constructor.
`<?php
class Foo
{
public $database = null;
public $bar = 'baz';
public function __construct(PDO $databaseObject)
{
$this->database = $this->setDatabase($database);
$this->baz = $this->SomeotherComplicatedFunction();
}
public function setDatabase(PDO $database)
{
//Validate and make changes that only Foo3 needs
if ($database->getAttribute(PDO::ATTR_TIMEOUT) === null) {
$database->setAttribute(PDO::ATTR_TIMEOUT, 10000);
}
}
}`