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
Related
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
}
```
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 : )
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);
class Session{
protected $git = md5(rand(1,6));
public function __construct($config = array())
{
//// some code
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Here I can't assign a random value like this to variable called git. How can I do this if it is possible?
That random value need to be first time generated value only till the time it converts to Null.
Perform random inside your constructor,
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
$ses_id = $this->git;
}
public function _start_session()
{
//code again..
}
}
Try setting the value of your variable in your constructor.
constructor will run every time you create an instance of your class.
try this code:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
$this->git = md5(rand(1,6));
}
public function _start_session()
{
//code again..
}
}
:)
Declare a variable inside a class,initialize the variables in class inside a constructor, which sets the variables once the object for that class is declared anywhere in the code.
I updated this answer if you want to do not change your session variable on each constructor call then use the below procedure.
class Session{
protected $git;
public function __construct($config = array())
{
$this->git = md5(rand(1,6));
if(!isset($_SESSION['ses_id']))
{
$_SESSION['ses_id'] = $this->git;
}
}
public function _start_session()
{
//code again..
}
}
I hope this helps you.
Try this using a global variable to track the random number:
class Session{
protected $git;
public function __construct($config = array())
{
//// some code
if (!isset($GLOBALS['random_val'])) {
$GLOBALS['random_val'] = md5(rand(1,6));
}
$this->git = $GLOBALS['random_val'];
$ses_id = $this->git;
var_dump("Session ID: ".$ses_id);
}
public function _start_session()
{
//code again..
}
}
$ses1 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
$ses2 = new Session(); // Outputs string(44) "Session ID: 1679091c5a880faf6fb5e6087eb1b2dc"
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
//....Multiple Items
private $VVal_2000 = 2000; //For Example
private $VNam_2000 = "Two Thousands"; //For Example
private static $Hash = array(); //How to initialize???
private static function Assigning(){
//This function for to assign the array elements (initialize)
global $Hash;
$this->Hash = array(); //to empty Hash variable and not add more data than it should.
$this->Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
$this->Hash[$this->VVal_2000] = $this->VNam_2000;
}
public static function GetVal($Nam) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_search($Nam, $this->Hash))
return array_search($Nam, $this->Hash);
return -1;//error
}
public static function GetNam($Val) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_key_exists($Val, $this->Hash))
return $this->Hash[$Val];
return "Error";
}
}
Class Testing {
static $OtherVal = Assignation::GetVal("BLABLA"); //for example
static $OtherNam = Assignation::GetNam(20); //for example
//Other functions...
}
Hi, you can see my script or code php...
I need to initialize the Hash array, this have static word because I need to use it in other static function. And this "other function" need to use it for other static variable...
I need to know how to implement it the right way..
Thanks chep.-.
<?php
echo "pre-Class Assignation<br/>";
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
private $VVal_2K = 2000;
private $VNam_2K = "Two Thousands";
private static $Hash = array();
private static function Assigning(){
if(!empty(self::$Hash)) return;
self::$Hash[$this->VVal_1] = $this->VNam_1;
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
public static function GetVal($Nam) {
self::Assigning();
if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
return -1;//error
}
public static function GetNam($Val) {
self::Assigning();
if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
return "Error";
}
}
echo "post-Class Testing<br/>";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid<br/>";
echo Assignation::GetNam(20);
echo "post-Class Sample<br/>";
//Testing::MyPrint();
?>
This code is not running, somebody help me testing the code...
result:
pre-Class Assignation
post-Class Assignation
post-Class Testing
that mean:
" echo Assignation::GetVal("BLABLA");"
have error...
In Assigning(), try using self::$Hash rather than $this->Hash and remove the global $Hash. Same applies for calling Assigning(): self::Assigning() as your comments suggest.
$this references the current object, so you must use self:: for all static functions and member data when inside the class.
Also, if this is your real code and not just a sample, you may want to check whether you have already done initialization, otherwise you will be doing it for every call to GetVal() and GetNam(). You could do this by adding something like if(!empty(self::$Hash)) return at the beginning of Assigning()
EDIT
private static function Assigning() {
if(!empty(self::$Hash)) return; // already populated
self::$Hash = array();
self::$Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}