Access a variable nested in a function inside a class in php - php

Here is a cut down version of my code with the main class and main function
I need to get the value of 'userName' that input by the user to use it inside 'mainFunction', tried making the 'userName' inside 'myForm' global but that didn't get the value out.
can value of 'userName' be available out side 'mainClass' so that I can use it anywhere?
class mainClass {
function myForm() {
echo '<input type="text" value="'.$userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $GLOBALS['userName']
)
}

class mainClass {
public $username;
function __construct($username){
$this->username = $username;
}
function myForm() {
echo '<input type="text" value="'.$this->userName.'" />';
}
}
function mainFunction () {
$myArray = array (
'child_of' => $this->username;
);
}

can value of 'userName' be available out side 'mainClass' so that I can use it anywhere?
Yes.
First, you need to define a class property like this
class MainClass
{
private $_userName;
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
Look at how you access this property inside the myForm() method.
Then you need to define getter method for this property (or you can make the property public) like this:
class MainClass
{
private $_userName;
public function getUserName()
{
return $this->_userName;
}
public function myForm()
{
echo '<input type="text" value="'.$this->_userName.'" />';
}
}
You can access user name property like this
$main = new MainClass();
$userName = $main->getUserName();
Note that you need an instance of the MainClass class.
I suggest you to start with simple concept and make sure you understand this 100%. Also I would suggest avoid using global variables and more complicated logic with static methods. Try to make it as simple as possible.
Warm regards,
Victor

The below code is a very minimized version of the Codeigniter get_instance method. So in your case you can have somewhere at the beginning this code:
/** Basic Classes to load the logic and do the magic */
class mainInstance {
private static $instance;
public function __construct()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance()
{
return mainInstance::get_instance();
}
new mainInstance();
/** ----------------------------------------------- */
and then you can create your global Classes like this:
class customClass1 {
public $userName = '';
function myForm() {
return '<input type="text" value="'.$this->userName.'" />';
}
}
/** This is now loading globally */
$test = &get_instance();
//If you choose to actually create an object at this instance, you can call it globally later
$test->my_test = new customClass1();
$test->my_test->userName = "johnny";
/** The below code can be wherever in your project now (it is globally) */
$test2 = &get_instance();
echo $test2->my_test->myForm()."<br/>"; //This will print: <input type="text" value="johnny" />
echo $test2->my_test->userName; //This will printing: johnny
As this is now globally you can even create your own function like this:
function mainFunction () {
$tmp = &get_instance();
return $tmp->my_test->userName;
}
echo mainFunction();

Related

How to output value of array which is set by php class?

I hope someone can help me with my problem. I'm still a beginner in PHP so sorry.
My code looks like this:
class Component
{
public $title;
// value if nothing gets set
public function __construct($title = "Test") {
$this->title = $title;
}
public function setTitle($value)
{
$this->title = $value;
}
public function getTitle()
{
return "Title: ".$this->title;
}
public function returnInfo()
{
$info = array(
'Titel' => $this->title,
);
return $info;
}
So in the class "Component" the functions should set and get a specific value. If nothing is set for a.e. title it should get the value "Test". With returnInfo() the informations like title should get returned.
My other class (where someone can add the informations like title) looks like this:
abstract class ComponentInfo extends Component
{
protected function getComponentInfo ()
{
$button1 = new Component;
$button1->setTitle("Button-Standard");
// should return all infos for button1
$button1Info = $button1->returnInfo();
foreach ($button1Info as $info)
{
echo ($info);
}
}
}
So it should work like this: in a other class named ComponentInfo a user can add a component like a button. Then the user can set informations like the title. And after that the information should get saved in an array and now I want to display all informations like this:
Title: Button-Standard
How can it work? And where is the mistake in my code?
It would be helpful to get a working code where the user can make as much ComponentInfo classes he want and where he can add different components with information that can be saved into an array.
And at the end it should get outputed as text on a main page.
You can't instantiate an abstract class. You need to remove the abstract keyword from the ComponentInfo class.
UPDATE given the info in your comment, I'd go this
Component.php
abstract class Component
{
private $key;
private $title;
public function __construct($key, $title) {
$this->setKey($key);
$this->setTitle($title);
}
public function setKey($key)
{
$this->key = $key;
}
public function getKey()
{
return $this->key;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function __toString()
{
return $this->getKey().': '.$this->getTitle();
}
}
ComponentInfo.php
class ComponentInfo extends Component
{
public function __construct($key='Info', $title='example title')
{
parent::__construct($key, $title);
}
}
And then use it in your code
somefile.php
$components = [];
$components []= new ComponentInfo();
$components []= new ComponentInfo('Different Key', 'Other info');
$components []= new ComponentNavigation('longitude', 'latidude'); //create another class like ComponentInfo
[... later you want to print this info in a list for example]
echo '<ul>';
foreach($components as $components) {
echo '<li>'.$component.'</li>'; //the __toString() method should get called automatically
}
echo '</ul>';
This should work, however, having different components with no other specificities than a different title and key is pointless. Instead, you could simply have different Components with a different key and title.

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)

Get variable from out of Class OOP 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
}
```

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

Use a variable from __construct() in other methods

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

Categories