Call variable from a function that's inside a class? - php

I just created my first PHP class, but I'm very new to this and now I don't know how to call a variable inside a function that I created.
For example:
class Example
{
public function testFunction() {
$var1 = "Test";
$var2 = "Hello";
}
}
And then, for example, echo $var1.
I know that I can call the function through this:
$something = new Example();
$something->testFunction();
But how can I call one of those variables inside the function?
I also know that if the variable was outside the function, it would be:
$something = new Example();
echo $something->var1;
I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function.
I hope that you can help me.

Variables inside functions aren't available outside them. The function needs to return the variable.
i.e.
function getName(){
return "helion3";
}
echo $myClass->getName();
If you need more than one, return an array:
return array("name1","name2");

To access variables from outside class functions like that, you need to set the variables as properties of the class:
class Example {
public $var1 = '';
private $var3 = ''; // private properties etc are not available outside the class
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
}
}
$something = new Example();
echo $something->var1; // Test
echo $something->var2; // can't do this at all (it's not an object property)
echo $something->var3; // can't do this, it's private!
Of course, you can return whatever you like from the function itself...
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
return array($this->var1, $var2, $this->var3);
}
You can return private properties and locally scoped variables...
list($var1, $var2, $var3) = $something->testFunction(); // all there!

Variables declared inside your function are only accessible within the function body.
If your function needs to return more than one value, you either a) return a new object, or b) return an array:
return [$var1, $var2];
And in the calling code:
list($a, $b) = $something->testFunction();

Related

Codeigniter access variable data which is defined on function1 on function2

I have two functions in a class. What i need is something like this (This is incorrect)
class Home{
function one(){
$var1 = "abc";
}
function two(){
$var2 = $var1;
echo $var2; //This needs to output 'abc' for me.
}
}
Unfortunately, it is not working.
Can somebody help me please.
There are many ways to achieve this, one of the ways is mentioned below, if you're learning OOP then I'd suggest watching mmtuts videos which are quite informative.
<?php
class Home{
public $var1 = 'xyz';
function one($x){ // or public function ...
$this->var1 = $x;
}
function two(){ // or public function ...
$var2 = $this->var1;
echo "var2: {$var2}"; //This needs to output 'abc' for me.
}
}
$xyz = new Home(); // instantiate the class
$xyz->one('abc'); // call the function, pass the variable
$xyz->two(); // get the value

Use list of variables as arguments when defining php function

I am trying to use a list of variables as arguments when DEFINING a function. It seems like it should be straight forward, but no. The callback is easy and I am able to use (...$listOfVariables) to get all needed arguments into callback, but it does not work when defining the function.
I need this because I have 50 different functions that require the use all of the same arguments. When the list of arguments changes (which it does) I need a central location to make sure all of the different functions use the new list of arguments. (Again, I already can do this with the callback, but not when I define the function)
Here is how I would normally do it for a few arguments.
$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';
function funcname($var1, $var2, $var3){
echo $var1;
}
That works fine, but my list of variables changes a lot and is used in many other functions. I may be going about it the wrong way and I'm open to whatever suggestions you have. Below is what I need to accomplish.
EDITED
1.variables that are defined outside of the function
$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';
2.a variable that contains all of those variables
$listOfVar = $var1, $var2, $var3; //***see note below***.
3.include list of variables that I can use within the function so I don't have to list them one at a time like I did in the first snippet.
function funcname($listOfVar){
echo $var1;
}
the full code I am trying to make work:
$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';
$listOfVar = $var1, $var2, $var3;
function funcname($listOfVar){
echo $var1;
}
**I realize the commas in the $listOfVar syntax is not correct for this, but what IS the syntax then? I've tried variable variables ($$) - trying to convert a string to variable name references. I have tried arrays. I have tried literally hundreds of variations of these and I am just out of ideas for this. Please help.
If you do not know in advance how many variables does the end developper will use on your function, you can use func_get_args(). It returns every variables values as an array.
Here is an example of usage:
function foo() {
$arguments = func_get_args();
return $arguments;
}
print_r(foo(1, 2, 3)); // [1, 2, 3]
print_r(foo('a', 'b', 'c')); // ['a', 'b', 'c']
I used this function because you mentioned the fact that you do not know in advance how many parameters the end developper is going to put.
If instead you use an array for the passed data...
function funcname($vars){
echo $vars[0];
}
Although it has advantages not sure if this would be a good idea, but you could also use an associative array...
function funcname($vars){
echo $vars['var1'];
}
Maybe you could modify your function so that it takes an array instead of multiple arguments.
function funcname(array $args){
foreach ($args as $arg_name => $arg) {
// do stuff with $arg_name and $arg
}
// or refer to a specific argument, like where you would have said $var1, instead...
$args['var1'];
// or extract the array within your function to get the keys as variables
extract($args);
echo $var1;
// If you do this, be sure to heed the warnings about extract.
// Particularly the bit about not extracting $_GET, $_POST, etc.
}
Then instead of defining separate variables like
$var1 = 'var1text';
$var2 = 'var2text';
$var3 = 'var3text';
Create an associative array
$text['var1'] = 'var1text';
$text['var2'] = 'var2text';
$text['var3'] = 'var3text';
If you have multiple functions that need to use the same varying list of arguments, I think it makes sense to collect them in a class. Then you can pass the associative array of arguments to the class constructor so all the methods will have access to the same set of variables.
class SomeFunctions
{
private $listOfVar = [];
public function __construct(array $listOfVar) {
$this->listOfVar = $listOfVar;
}
public function funcnameA() {
foreach ($this->listOfVar as $name => $value) // ...
}
public function funcnameB() {
$this->listOfVar['var1'];
}
}
$example = new SomeFunctions(['var1' => 'something', 'var2' => 'something']);
$example->funcnameA();
$example->funcnameB();
If you need to use these functions as callbacks, you can pass them like this as the callback parameter:
functionThatTakesaCallback([$example, 'funcnameB']);
Maybe this could be the central location to change the variable list?
In future, read How to create a Minimal, Complete, and Verifiable example so we can understand your question in order to help you.
Methods have there own scope, meaning unless otherwise declared or passed through, the method will not have access to the variable.
class Retriever {
private static $instance;
protected $listOfVars = array();
public static function getInstance() {
if(self::$instance) return self::$instance;
self::$instance = new self();
return self::$instance;
}
private function __construct() {}
public function addVar($var) { array_push($this->listOfVars, $var); return $this; }
public function getVars() { return $this->listOfVars; }
public function reset() { $this->listOfVars = array(); return $this; }
}
function name($var1, $var2, $var3) {
echo $var1;
}
function anotherName($var1, $var2) {
echo $var2;
}
Retriever::getInstance()->addVar("var1text")->addVar("var2text")->addVar("var3text");
name(...Retriever::getInstance()->getVars()); # Output: var1test
Retriever::getInstance()->reset()->addVar("var1text")->addVar("var2text");
anotherName(...Retriever::getInstance()->getVars()); # Output: var2text
Live demo.
Or you can use the list() method
function name($listOfVars) {
list($var1, $var2) = $listOfVars;
echo $var1;
}
name(array(‘var1text’, ‘var2text’));
Simply put your variables in an array and pass the name of the array to your function.
$vararray[] = 'var1text';
$vararray[] = 'var2text';
$vararray[] = 'var3text';
funcname($vararray);
function funcname($variable_array){
echo $variable_array[1]; // will echo var2text
}

outer variables define inside a class

how do you define a variable in a class? seems like global only works inside the function.
<?php
$a = '20';
$b = '10';
class test {
global $a; $b;
function add() {
echo $a;
}
}
$answer = new test();
$answer->add();
?php>
i tried this one (use global inside a class but gets error instead)
also, how can you define multiple variables in just 1 line of code instead of defining it each.
To define a class property (or variable), you would do like so:
class Foo {
private $myVar = 'my var'; // define a class property
public function add() {
echo $this->myVar;
}
}
How about passing the data in via the constructor?
Code: (Demo)
$a_outside = '20';
$b_outside = '10';
class test {
public $a_inside;
public $b_inside;
public function __construct($a_passed_in, $b_passed_in)
{
$this->a_inside = $a_passed_in;
$this->b_inside = $b_passed_in;
}
public function add()
{
echo $this->a_inside + $this->b_inside;
}
}
$answer = new test($a_outside, $b_outside);
$answer->add(); // output: 30
Pass the variable to the class via arguments in the constructor call.
Define the values as variables in the class within construct call.
Access the variables within the add() method.

PHP: assign function to class method

How can I assign a function to a method in a class in PHP? I tried the following:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar')
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName))
continue;
$this->{$functionName}() = function($params){ //should create the methods "foo" and "bar"
echo $variable; //should echo 'blablabla' (I know that the variable was declared outside this function, but how can I access it anyway?)
}; //the error points to here
}
}
}
But this code gives me this error:
Fatal error: Can't use method return value in write context
Does anyone know how I can assign the anonymous function to the class method, while also still being able to access variables outside that function?
You are doing foreach($functionNames as $functionName){ which means that $functionName is a string, not an array. So, don't use $functionName[0].
method_exists takes 2 parameters. One is the object and the other is the method name. It should be:
method_exists($this, $functionName)
As for creating the function, you don't need () on the left side of the =. It should be:
$this->$functionName = function($params) use($variable){
echo $variable;
};
The use($variable) is needed to tell PHP to use that variable inside the function. That's how closures work in PHP, it's different than other languages.
So, your class should look like:
class Something{
public function __construct(){
$functionNames = array('foo', 'bar');
$variable = 'blablabla';
foreach($functionNames as $functionName){
if(method_exists($this, $functionName)){
continue;
}
$this->$functionName = function($params) use($variable){
echo $variable;
};
}
}
}
Problem here is that in this way of making functions, you are not actually creating a class method, but instead creating a class variable that contains a function.
So, you need to call it like so:
$test = new Something;
$foo = $test->foo;
$foo('abc');
You can't just do $test->foo('abc');.
EDIT: Another thing you can do is use PHP's __call "magic method". This will be ran whenever you do ->funcName(), regardless of whether the method exists or not. Using that method, you can just check to see if the method called was 'foo' or 'bar'. See this example:
class Something{
private $variable;
public function __construct(){
$this->variable = 'blablabla';
}
public function __call($name, $params=array()){
if(method_exists($this, $name)){
// This makes sure methods that *do* exist continue to work
return call_user_func(array($this, $name), $params);
}
else{
$functionNames = array('foo', 'bar');
if(in_array($name, $functionNames)){
// You called ->foo() or ->bar(), so do something
// If you'd like you can call another method in the class
echo $this->variable;
}
}
}
}
With this, now you can do the following:
$test = new Something;
$test->foo('abc'); // Will echo "blablabla"

Reset Class Instance Variables via Method

Does anyone know how to reset the instance variables via a class method. Something like this:
class someClass
{
var $var1 = '';
var $var2 = TRUE;
function someMethod()
{
[...]
// this method will alter the class variables
}
function reset()
{
// is it possible to reset all class variables from here?
}
}
$test = new someClass();
$test->someMethod();
echo $test->var1;
$test->reset();
$test->someMethod();
I know I could simply do $test2 = new SomeClass() BUT I am particularly looking for a way to reset the instance (and its variables) via a method.
Is that possible at all???
You can use reflection to achieve this, for instance using get_class_vars:
foreach (get_class_vars(get_class($this)) as $name => $default)
$this -> $name = $default;
This is not entirely robust, it breaks on non-public variables (which get_class_vars does not read) and it will not touch base class variables.
Yes, you could write reset() like:
function reset()
{
$this->var1 = array();
$this->var2 = TRUE;
}
You want to be careful because calling new someClass() will get you an entirely new instance of the class completely unrelated to the original.
this could be easy done;
public function reset()
{
unset($this);
}
Sure, the method itself could assign explicit values to the properties.
public function reset()
{
$this->someString = "original";
$this->someInteger = 0;
}
$this->SetInitialState() from Constructor
Just as another idea, you could have a method that sets the default values itself, and is called from within the constructor. You could then call it at any point later as well.
<?php
class MyClass {
private $var;
function __construct() { $this->setInitialState(); }
function setInitialState() { $this->var = "Hello World"; }
function changeVar($val) { $this->var = $val; }
function showVar() { print $this->var; }
}
$myObj = new MyClass();
$myObj->showVar(); // Show default value
$myObj->changeVar("New Value"); // Changes value
$myObj->showVar(); // Shows new value
$myObj->setInitialState(); // Restores default value
$myObj->showVar(); // Shows restored value
?>

Categories