Skip to content

Instantly share code, notes, and snippets.

@wesbasinger
Last active February 1, 2019 13:40
Show Gist options
  • Save wesbasinger/ea43fc7703f7759eba6b46c9d5831c5c to your computer and use it in GitHub Desktop.
Save wesbasinger/ea43fc7703f7759eba6b46c9d5831c5c to your computer and use it in GitHub Desktop.
Member Variables in a Class
// 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";
}
}
@php-bob
Copy link

php-bob commented Feb 1, 2019

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);
}
}
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment