Use a variable from __construct() in other methods - php

I defined a new variable in __construct() and I want to use it in another function of this class.
But my variable is empty in the other function!
this is my code:
class testObject{
function __construct() {
global $c;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
global $data;
print_r($data);
}
}

Declare variable $data as global inside the constructor:
function __construct() {
global $c;
global $data;
$data = array("name"=>$c['name'],
"family"=>$c['family']);
}
Then, it will be visible in other function as well.
Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.
A more proper way would be to use
class testObject
{
private $data;
function __construct(array $c)
{
$this->data = array(
"name"=>$c['name'],
"family"=>$c['family']
);
}
function showInfo()
{
print_r($this->data);
}
// getter: if you need to access data from outside this class
function getData()
{
return $this->data;
}
}
Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.
class testObject
{
private $name;
private $family;
function __construct($name, $family)
{
$this->name = $name;
$this->family = $family;
}
function showInfo()
{
print("name: " . $this->name . ", family: " . $this->family);
}
// getters
function getName()
{
return $this->name;
}
function getFamily()
{
return $this->family;
}
}
And you can even construct this object with data from you global variable $c until you elimitate it from your code:
new testObject($c['name'], $c['family'])

You can do this way. Instead of declaring $data as global variable declare as public or private or protected variable inside the class depending on your use. Then set the data inside _construct.
Using global inside a class is not a good method. You can use class properties.
class testObject{
public $data;
function __construct() {
global $c;
$this->data = array("name"=>$c['name'],
"family"=>$c['family']);
}
function showInfo() {
print_r($this->data);
}
}

Related

How to access global variable from inside class's function

I have file init.php:
<?php
require_once 'config.php';
init::load();
?>
with config.php:
<?php
$config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>
A class with name something.php:
<?php
class something{
public function __contruct(){}
public function doIt(){
global $config;
var_dump($config); // NULL
}
}
?>
Why is it null?
In php.net, they told me that I can access but in reality is not .
I tried but have no idea.
I am using php 5.5.9.
The variable $config in config.php is not global.
To make it a global variable, which i do NOT suggest you have to write the magic word global in front of it.
I would suggest you to read superglobal variables.
And a little bit of variable scopes.
What I would suggest is to make a class which handles you this.
That should look something like
class Config
{
static $config = array ('something' => 1);
static function get($name, $default = null)
{
if (isset (self::$config[$name])) {
return self::$config[$name];
} else {
return $default;
}
}
}
Config::get('something'); // returns 1;
Use Singleton Pattern like this
<?php
class Configs {
protected static $_instance;
private $configs =[];
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
private function __clone() {
}
private function __wakeup() {
}
public function setConfigs($configs){
$this->configs = $configs;
}
public function getConfigs(){
return $this->configs;
}
}
Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);
class Something{
public function __contruct(){}
public function doIt(){
return Configs::getInstance()->getConfigs();
}
}
var_dump((new Something)->doIt());
Include the file like this:
include("config.php");
class something{ ..
and print the array as var_dump($config); no need of global.
Change your class a bit to pass a variable on the constructor.
<?php
class something{
private $config;
public function __contruct($config){
$this->config = $config;
}
public function doIt(){
var_dump($this->config); // NULL
}
}
?>
Then, if you
include config.php
include yourClassFile.php
and do,
<?php
$my_class = new something($config);
$my_class->doIt();
?>
It should work.
Note: It is always good not to use Globals (in a place where we could avoid them)

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 : )

Creating a new class object and setting variables directly - PHP

I am trying to understand how to efficiently create a new class object and set the variables directly.
I have a class:
class element_model
{
public $sType;
public $properties;
}
I have a controller in which the following function is defined:
public function create_element($sType, $properties)
{
$oElement_model = new element_model($sType, $properties);
return new element_model($sType, $properties);
}
But this does not returns a new element_model with properties set, it just returns an empty object.
It does not, however, throw an error.
What is the reason the function above does not work?
You have to pass to the constructor of the class, in PHP you should have a method in the class __construct :
class element_model
{
public $sType;
public $properties;
public function __construct($type, $property)
{
$this->sType = $type;
$this->properties = $property;
}
}
Then you can access them (note the variables are public)
$elem = new element_model($sType, $properties);
$elem->sType;
Although in some cases it is better to encapsulate vars (declare them private):
class element_model
{
private $sType;
private $properties;
public function __construct($type, $property)
{
$this->sType = $type;
$this->properties = $property;
}
public function getType()
{
return $this->sType;
}
public function getProperty()
{
return $this->properties;
}
}
Then you can access the variable through a getter
$elem = new element_model($sType, $properties);
$elem->getType(); //and
$elem->getProperty();
You must create a __construct function in your class that accepts the parameters and sets your variables. Like this:
class element_model{
.
.
.
public function __construct($type,$properties)
{
$this->sType = $type;
$this->properties = $properties;
}
}
The __construct function will be called when you create the object.
But if you want to be extra cool in programming, just define your properties as private and create getter and setter functions to access the variables of your object
private $sType;
public function getSType(){
return $this->sType;
}
public function setSType($value){
$this->sType = $value;
}

passing variables from a protected function to a public function inside the same class in php

I have a class and two functions inside it as follows:
class MyClassName
{
protected function myFunction1()
{
// some code here
return $something;
}
public function myFunction2()
{
// some code here
return $somethingElse;
}
}
What I need to do is define a variable in myFunction1() and then use it in myFunction2(). What is the best practice to do that?
class MyClassName
{
public $var = 0;
protected function myFunction1()
{
// some code here
$this->var = ...;
return $something;
}
public function myFunction2()
{
// some code here
echo $this->var;
return $somethingElse;
}
}
Actually vars should be defined out of the function and then set a value. Then can be modified over all the script, by doing this->var
Make it a class property
class MyClassName
{
private $property;
public function __construct() {
$this->myFunction1();
}
protected function myFunction1()
{
// some code here
$this->property = 'an apple';
}
public function myFunction2()
{
// some code here
return $this->property;
}
}
Now test it:
$my_class = new MyClassName();
$something = $my_class->myFunction2();
echo $something;

Global variable without having to redeclare every function?

I want to have access to a global variable without having to redeclare every function. Here is an example.
$mobile = 1;
class Database
{
private $connect;
function one($argumentarray)
{
global $mobile;
echo $mobile;
}
function two($argumentarray)
{
global $mobile;
echo $mobile;
}
function three($argumentarray)
{
global $mobile;
echo $mobile;
}
}
I have about 100 functions and i need access to the $mobile variable in all of them. Is there a way to do this without having to do global $mobile in every function?
The best way would be to NOT use the global. Design your program in a way that it can live without globals. That's it.
A simple design that comes in mind, might look like:
class Configuration {
protected static $mobile = 1;
// let's say it's write protected -> only a getter.
public static mobile() {
return self::$mobile;
}
}
class Database {
// use the config value
function one() {
if(Configuration::mobile()) {
...
}
}
}
Use the $GLOBALS array.
$GLOBALS["mobile"]
Or you could store the variable in your class - which is cleaner in my opinion.
Well, You could do something like this:
class Database
{
private $connect;
private $mobile;
function __construct() {
#assign a value to $mobile;
$this->mobile = "value";
}
function one($argumentarray)
{
echo $this->mobile;
}
function two($argumentarray)
{
echo $this->mobile;
}
function three($argumentarray)
{
echo $this->mobile;
}
}
Already 5 answers and nobody mentioned static class variables yet.
Copying the variable in the constructor would be wasteful, impractical and hurt readability. What if you need to change the value of this global later on? Every object will be stuck with an obsolete copied value. This is silly.
Since you need a prefix to access this "global" anyway, let it be self:: or Database:: rather than this-> :).
It will
allow you to set the variable directly from the class definition,
not waste memory doing a copy of it for each object
make it accessable from outside if you whish so (if you declare it public)
In your example:
class Database {
static private $mobile = "whatever";
function one($argumentarray)
{
echo self::$mobile;
}
function two($argumentarray)
{
echo self::$mobile;
}
function three($argumentarray)
{
echo self::$mobile;
}
}
If you want to allow modifications from outside :
static private $mobile;
static function set_mobile ($val) { self::$mobile = $val; }
static function get_mobile ($val) { return self::$mobile; }
or
static public $mobile;
Maybe a class attribute, and set it with the constructor?
class myClass {
private $mobile;
/* ... */
}
In the constructor, do:
public function __construct() {
$this->mobile = $GLOBALS['mobile'];
}
And then use:
$this->mobile
from everywhere!
Pass the variable to the constructor, and set a class level variable.
It can then be accessed in the varius methods using $this->
$mobile = 1;
class Database
{
private $connect;
private $mobile
function __construct($mobile){
$this->mobile=$mobile;
}
function one($argumentarray)
{
echo $this->mobile;
}
function two($argumentarray)
{
echo $this->mobile;
}
function three($argumentarray)
{
echo $this->mobile;
}
}
$db = new Database($mobile);

Categories