Last active
November 8, 2023 08:38
-
-
Save agenticsim/7382545 to your computer and use it in GitHub Desktop.
PHP Procedural vs. Object-Oriented Programming (OOP)
This file contains hidden or 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
<?php | |
// Procedural | |
function example_new() { | |
return array( | |
'vars' => array() | |
); | |
} | |
function example_set($example, $name, $value) { | |
$example['vars'][$name] = $value; | |
return $example; | |
} | |
function example_get($example, $name) { | |
$value = isset($example['vars'][$name]) ? $example['vars'][$name] : null; | |
return array($example, $value); | |
} | |
$example = example_new(); | |
$example = example_set($example, 'foo', 'hello'); | |
list($example, $value) = example_get($example, 'foo'); | |
// OOP | |
class Example | |
{ | |
private $vars = array(); | |
public function set($name, $value) | |
{ | |
$this->vars[$name] = $value; | |
} | |
public function get($name) | |
{ | |
return isset($this->vars[$name]) ? $this->vars[$name] : null; | |
} | |
} | |
$example = new Example(); | |
$example->set('foo', 'hello'); | |
$value = $example->get('foo'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The procedural style could be even better or clearer using namespaces.
And then in another script (or namespace):