Codeigniter access variable data which is defined on function1 on function2 - php

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

Related

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
}

How to make function from string variables?

How to make function from string? I am new to php programming and wanted solution for below code.
If I want to access page for test2.php?page=test for below class:
class test{
public static function getTest(){
//code here....
};
}
and wanted to access test2.php?page=test using variable so what should I do?
require_once "test.php";
$variabe = $_GET['page'];
test::get . ucfirst($variable) . ();
You can do it like this:
<?php
class test{
public static function getTest(){
echo 'getTest()!!';
}
}
$variable = 'Test';
// since we are interpolating a raw string, input from $_GET, and a function we need to let PHP know to fully complete this string before using it as a function call
test::{"get".ucfirst($variable)}();
// Build the full method name ahead of time and you can just call it using the variable
$variable2 = 'getTest';
test::$variable2();
Output:
getTest()!!

PHP using vars inside a function without pasing param

In the following code; is there a way to use the vars inside the function without having to pass them as params?
$var1 = 'test';
$var2 = 'another';
function testing(){
print $var1;
}
I read up on the php global's but wasn't sure if it was a good idea.
I have an ajax call that gets about 25 vars and replaces the tags in the body of an email where the placeholders are.
The sendEmail piece is in a function and needs access to the outside vars to be able to replace the content.
Without having a function(){} with 25 vars in it, is there another way to acomplish this?
UPDATE
Here is a sample snippet of my code; the reason why I am trying to do this.
http://pastebin.com/8qYsLg5T
You can do as the answer above make vars global.Kinda bad practice and you will end up overwriting them if you re use them and it makes them available for attacks.
What you should be doing(is writing them out) but if that is to much then making the vars an array then passing them as an array. Chances are your getting the data in an array form.
$vars = array(
'varname1' => 'var_value1',
'varname2' => 'var_value2',
'varname3' => 'var_value3',
);
do_stuff_with_vars($vars);
You could quickly create an array as someone else here suggested by using compact.
compact(var,var2,etc);
Your function should look something like
function do_stuff_with_vars($array){
//do stuff with array["varnameX"]
}
You can use compact() to put all of the variables in an array, then pass that to your function.
<?php
$data = compact($var1, $var2, $var3, $var4);
testing($data);
function testing($data) {
print $data['var1'];
print $data['var2'];
// Or, if you don't want to use an array here, use extract() to do the
// opposite of compact():
extract($data);
print $var3;
print $var4;
}
$my_array = array(
'element1' => $var1,
'element2' => $var2
);
function testing($my_array){
print $my_array['element1'];
// or use foreach()
}
The best way is using oop
class A {
public $var = 'test';
public $var2;
public function test(){
print $this->var;
}
}
$a = new A();
$a->test();
$var1 = 'test';
$var2 = 'another';
function testing(){
global $var1;
print $var1;
}
You shouldn't use globals, use OOP. You could create a class as a holder for the 25 parameters and use them from your send function
class MyMail {
public $user;
public $subject;
public $body;
public function send() {
// do the send
mail($this->user, $this->subject, ...);
}
}
$mailSender = new MyMail();
$mailSender->user = 'a#b.com';
$mailSender->subject = 'Hello';
$mailSender->send();

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

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

How can I create a function dynamically?

I have a variable like $string = "blah";
How can I create a function that has the variable value as name?
Is this possible in PHP?
Like function $string($args){ ... } or something, and be able to call it like:
blah($args);
this might not be a good idea, but you can do something like this:
$string = "blah";
$args = "args"
$string = 'function ' . $string . "({$args}) { ... }";
eval($string);
That doesn't sound like a great design choice, it might be worth rethinking it, but...
If you're using PHP 5.3 you could use an anonymous function.
<?php
$functionName = "doStuff";
$$functionName = function($args) {
// Do stuff
};
$args = array();
$doStuff($args);
?>
Okay, challenge accepted!
No matter how weird the question is (it's not btw), let's take it seriously for a moment! It could be useful to have a class that can declare functions and make them real:
<?php
customFunctions::add("hello", // prepare function "hello"
function($what) {
print "Hello $what, as Ritchie said";
print "<br>";
}
);
customFunctions::add("goodbye", // prepare function "goodbye"
function($what,$when) {
print "Goodbye cruel $what, ";
print "I'm leaving you $when";
print "<br>";
}
);
eval(customFunctions::make()); // inevitable - but it's safe!
That's it! Now they're real functions. No $-prefixing, no runtime evaluations whenever they get called - eval() was only needed once, for declaration. After that, they work like any function.
Let's try them:
hello('World'); // "Hello World"
goodbye('world','today'); // "Goodbye cruel world, I'm leaving you today"
Magic behind
Here's the class that can do this. Really not a complex one:
class customFunctions {
private static $store = [];
private static $maker = "";
private static $declaration = '
function %s() {
return call_user_func_array(
%s::get(__FUNCTION__),
func_get_args()
);
}
';
private static function safeName($name) {
// extra safety against bad function names
$name = preg_replace('/[^a-zA-Z0-9_]/',"",$name);
$name = substr($name,0,64);
return $name;
}
public static function add($name,$func) {
// prepares a new function for make()
$name = self::safeName($name);
self::$store[$name] = $func;
self::$maker.=sprintf(self::$declaration,$name,__CLASS__);
}
public static function get($name) {
// returns a stored callable
return self::$store[$name];
}
public static function make() {
// returns a string with all declarations
return self::$maker;
}
}
It provides an inner storage for your functions, and then declare "real" functions that call them. This is something similar to fardjad's solution, but with real code (not strings) and therefore a lot more convenient & readable.
Try call_user_func_array()
php.net link
You can call a function by its name stored in a variable, and you can also assign a function to variables and call it using the variable. If it's not what you want, please explain more.

Categories