Get variable from out of Class OOP PHP - php

I wanna get variable from out of class.
Example,
config.php
$config['function'] = array('filter_validate','form');
controller.php
class Controller{
public function __construct()
{
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
But, I can't get $config['function'] variable in Controller. How can do that?

Solution #1 (with parameter):
class Controller {
public function __construct($config) {
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
Solution #2 (with global - NOT recommended):
class Controller {
public function __construct() {
global $config;
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}

You need to pass config to the constructor, like this:
class Controller{
public function __construct($config)
{
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
$config['function'] = array('filter_validate','form');
$controller = new Controller($config);

functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables.
<?php
function abc() { }
$foo = 'bar';
class SomeClass {
public function tada(){
global $foo;
abc();
echo 'foo and '.$foo;
}
}
?>

There are many ways, the most modern right now is with a fluent, getter / setter. one one of many examples, not tested:
public function config(array|string $arg, array|string $default)
{
// assume lonley arg is a getter
if(is_string($arg)) return $this->variableBag[$arg];
// assume arg is a setter when array
if(is_array($arg)) return $this->variableBag[$arg[0]??$arg['key'] = ?? $arg['1'] ?? $arg['value'];
// else assume if second is set a default val
return isset($this->variableBag[$default]) ?$this->variableBag[$default] : $default
}
```

Related

How do I set PHP class properties with construct() arguments automatically?

Does anyone know of an efficient technique in PHP to auto assign class parameters with identically named __construct() method arguments?
For instance, I've always thought it was highly inefficient to do something like the following:
<?php
class Foo
{
protected $bar;
protected $baz;
public function __construct($bar, $baz)
{
$this->bar = $bar;
$this->baz = $baz;
}
}
I'm wondering if there's a better/more efficient way/magic method to auto-assign class properties with identically named method parameters.
Thanks,
Steve
PHP 8
Constructor Promotion
function __construct(public $bar, public $baz) {}
PHP 5
function _promote(&$o) {
$m = debug_backtrace(0, 2)[1];
$ref = new ReflectionMethod($m['class'], $m['function']);
foreach($ref->getParameters() as $i=>$p) {
$o->{$p->name} = $m['args'][$i] ?? $p->getDefaultValue();
}
}
class Foo {
function __construct($bar, $baz) {
_promote($this);
}
}
I think this way is a pretty generally accepted way to do it, although you could make getters and setters. Or, if you're looking for magic methods in php: http://php.net/manual/en/language.oop5.magic.php
Not in a constructor. You can always wrap your properties into an array, instead, and only have a single property that needs to be set:
<?php
class SomeClass
{
protected $data = [];
public function __construct(array $data = [])
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
}
$params = ['bar' => 'bar', 'baz' => 'baz'];
$someClass = new SomeClass($params);
echo $someClass->getData()['bar'] . PHP_EOL;
There is the magic method __set, but it is only called when attempting to write data to inaccessible properties:
<?php
class SomeClass
{
protected $data = [];
public function __construct(array $data = [])
{
$this->data = $data;
}
public function __set($name, $value)
{
$this->data[$name] = $value;
}
public function __get($name)
{
if(isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
}
$class = new SomeClass;
$class->bar = 'bar';
$class->baz = 'baz';
echo $class->bar . PHP_EOL . $class->baz . PHP_EOL;
If your class is starting to have a lot of parameters being passed in to the constructor, it may be a sign that your class is getting too big and trying to do too much. A refactoring may be in order.

Using global variable in my class causing unexpected syntax

I have a class that requires a variable that is defined out of the scope of it. So i tried using global but, this causes this error:
syntax error, unexpected 'global' (T_GLOBAL), expecting function (T_FUNCTION)
I am unsure if I have put it in the wrong place or using the global keyword incorrectly.
My code looks like this:
$data = new testClass();
class System
{
private $values;
global $data;
public function __construct()
{
}
public function test()
{
return $data->get();
}
}
$system = new System();
echo $system->test();
So i was wondering how do I get the $data variable to be defined in my class? My use of global seems to be incorrect, I also put the global declaration in the __contrust() function but that didn't work either.
Define the global variable within the function instead of the class:
public function test()
{
global $data;
return $data->get();
}
EDIT: Alternate idea:
class System
{
private $values;
private $thedata;
public function __construct($data)
{
$this->thedata = $data;
}
public function test()
{
return $this->thedata->get();
}
}
$data = new testClass();
$system = new System($data);
echo $system->test();
So i was wondering how do I get the $data variable to be defined in my class? My use of global seems to be incorrect, I also put the global declaration in the __contrust() function but that didn't work either.
If you really want to use bad global construction, you should do like this:
class System
{
private $values;
// removed global from here
public function __construct()
{
}
public function test()
{
// added global here
global $data;
return $data->get();
}
}
But OOP principles recommend us to use composition, not global variables. So you can pass the $data into your another class via constructor or via setter. Here's some code implementing both approaches:
class testClass {
public function get()
{
echo __CLASS__.'::'.__FUNCTION__;
}
}
class System
{
private $values;
private $data;
public function __construct(testClass $data = null)
{
if ($data) {
$this->data = $data;
}
}
public function setData(testClass $data)
{
$this->data = $data;
}
public function test()
{
return $this->data->get();
}
}
$data = new testClass();
// via constructor
$system = new System($data);
// or via setter
$system = new System;
$system->setData($data);
echo $system->test();
You could pass $data when you instantiate the class and then assign it in the constructor, which will make it available to all the methods of the class.
class System {
public $data;
public function __construct($data) {
$this->data = $data;
}
public function index() {
echo $this->data;
}
}
$data = 'foo';
$system = new System($data);
echo $system->index();
outputs 'foo';
First things first... This could just be a simple "bad PHP syntax" issue. Look for forgotten ; or in my case... Forgetting that functions actually need the word function : )

PHP use variable from global space inside class

Hi I'm writing some code in PHP. I need to use a variable from the global scope inside my class but it doesn't work. I don't know if I need to use namespace or not and how ? Thank you
Sample :
<?PHP
$plantask_global_script = array("one", "two");
$plantask_global_config = array("three", "four");
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
static private $container = $myvar;
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
self::$container[] = $value;
} else {
self::$container[$offset] = $value;
}
}
public function offsetExists($offset)
{
return isset(self::$container[$offset]);
}
public function offsetUnset($offset)
{
unset(self::$container[$offset]);
}
public function offsetGet($offset)
{
return isset(self::$container[$offset]) ? self::$container[$offset] : null;
}
}
Try calling $myvar as a superglobal:
private static $container = $GLOBALS['myvar'];
Although, as Ron Dadon pointed out, this is generally bad practice in OOP.
EDIT:
I jumped the gun here. My above solution does not actually work, at least not for me. So, a better way to achieve this would be the following:
$myvar = array_merge($plantask_global_script, $plantask_global_config);
class Env implements ArrayAccess
{
private static $container = null;
public static function init($var)
{
self::$container = $var;
}
...
}
Env::init($myvar);

Create properties in a class with the names and values of all the variables passed to the constructor

I want to create properties in a class with the names of all of the variables passed to the constructor and with the same values.
I was able to do it with strings:
class test {
public function __construct() {
$args = func_get_args();
foreach($args as $arg) {
$this->{$arg} = $arg;
$this->init();
}
}
public function init() {
echo $this->one;
}
}
// Output: "one"
$obj = new test("one");
But I don't know how I can do it with variables. I tried this:
class test {
public function __construct() {
$args = func_get_args();
foreach($args as $arg) {
$this->{$arg} = $arg;
$this->init();
}
}
public function init() {
echo $this->one;
}
}
$one = "one!";
$obj = new test($one);
Output:
Notice: Undefined property: test::$one on line 13
What I wanted it to output:
one!
Try:
public function init() {
echo $this->{'one!'};
}
No, it's not possible in any sane way to get the name of a variable used in calling code inside the callee. The sanest method is to use new test(compact('one')), which gives you a regular key-value array inside test::__construct, which you can loop through.
http://php.net/compact

How to pass php variable into a class function?

I want to pass php variable $aa into a class function. I have read some articles
in php.net, but I still don't understand well. Can anyone help me put the variable into this class? thanks.
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct() {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
Simply put the variable names in the constructor.
Take a look at the snippet below:
public function __construct( $aa )
{
// some content here
}
I'm not sure what you mean... do you mean you want to access $aa in a function? If so:
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct() {
global $aa;
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
Or, on a per instance basis, you can do things like:
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
new Action($aa);
$aa='some word';
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
And use it like this:
$instance = new Action('something');
I don't know php, but my logic and google say this:
class Action {
private $_objXML;
private $_arrMessages = array();
public function __construct($aa) {
$this->_objXML = simplexml_load_file($aa.'.xml');
}
}
$object = new Action('some word');
This is simply called pass a variable as parameter of a function, in this case the function is the constructor of Action

Categories