Passing a variable to its parent function in PHP? - php

I have a function w/in a function, and I need the inner function to make it's variables available in a scope of parent function, e.g.:
function sayMyName(){
getName(); // inner function generates $name value
echo $name; // use $name
}
sayMyName();
I could easily just globalize things w/in both functions... But my situation is far more complicated and handles more variables and globalizing each one is a bit tedious.
Thanks.
PS
i noticed a lot of "return" suggestions. sorry i wasnt clear , i need to return more variables.. not a simple return. thanks guys

You may use $_GLOBALS, but it`s a "bad practice". So,
1: Use return:
<?php
function getName(){
$name = 'Smith';
return $name;
}
function sayMyName(){
$name = getName();
echo $name;
}
sayMyName();
?>
Shows:
Smith
2: Use references:
<?php
function getName(&$name){
$name = 'Smith';
}
function sayMyName(){
getName($name);
echo $name;
}
sayMyName();
?>
Shows:
Smith
3: Return array for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
return array($surname, $name);
}
function sayMyName(){
list($surname, $name) = getName();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith
4. Return custom object for multiple variables:
<?php
function getName(){
$surname = 'Smith';
$name = 'John';
$buffer = new stdClass();
$buffer->name = $name;
$buffer->surname = $surname;
return $buffer;
}
function sayMyName(){
$obj = getName();
echo $obj->name, ' ', $obj->surname;
}
sayMyName();
?>
Shows:
John Smith
5. Use anonymous function with use statement and references:
<?php
function sayMyName(){
$surname = $name = 'Unknown';
$temp = function() use (&$name, &$surname){
$surname = 'Smith';
$name = 'John';
};
$temp();
echo $name, ' ', $surname;
}
sayMyName();
?>
Shows:
John Smith

do this
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results will be returned
}
sayMyName();
I hope your inner function is returning name like this
function getName(){
return $name;
}
then it will work

This is what the object oriented programming was designed for. If many functions should share variables, it is probably best to encapsulate them to class like this:
class WhateverDescibestYourViewOfTheWorld {
protected $name;
function __construct( $name)
{
$this->name = $name;
}
function GetName() {
return $this->name;
}
function SayName()
{
echo $this->name;
}
}
// And use it:
$o = new WhateverDescibestYourViewOfTheWorld();
...
$o->SayName();
Or you can build class which will be just used as data container:
class DataContainer {
public $name;
public $address;
// ...
}
// By reference this will modify object previously created
function GetProperties( &$dataContainer) // Note that & isn't necessary since PHP5
{
$dataContainer->name = "...";
}
$c = new DataContainer();
GetProperties($c);
Or you can simplify this and use array:
function GetProperties( array &$dataContainer)
{
$dataContainer['name'] = '...';
}
$data = array();
GetProperties($data);

What about first assigning the return value of getName() to a variable?
$name = getName();

If you only need one variable you can do this
function getName(){
// Some code
return 'my name is XXX';
}
function sayMyName(){
$name = getName(); // inner function generates $name value
echo $name; // results to undefined
}
sayMyName();
Otherwise you may consider using a class : http://www.php.net/manual/en/language.oop5.php

You can use references
$param = "aaa";
function f(&$param)
{
//dostuff
inner($param);
echo $param;
}
function inner(&$inner) { //do other stuff }
or use return value
function f() { echo inner(); }
function inner($param) {return $param;}
if you work on references, both functions will work on same variable, not on a copy
http://php.net/manual/en/language.references.php
the best way would be with class
<?php
class Person
{
private $name;
public function setName($name){ $this->name = $name;}
public function sayName() {echo $this->name;}
}
$person = new Person();
$person->setName("Robert");
$person->sayName();
It's good way to make it in OOP.

That what you are thinking is wrong, however you can return an array of values. For ex:
function sayMyName()
{
$result = getName(); // inner function creates an array
echo $result['name'];
}
or better an object:
class Results
{
public $name;
}
function sayMyName()
{
$result = getName(); // inner function creating an object
echo $result->name;
}

You can also do it as below.
$name = "";
function sayMyName(){
getName(); // inner function generates $name value
//set $name variable inside getName() function.
echo $name; // results to undefined
}
sayMyName();

Please use bellow code ,it will solve your problem
global $var;
You can use it anywhere within your php span.

Related

PHP: How do I create an interpolated string that changes when inner variables change?

I want to store a sentence in a variable. The sentences contains another variable.
php > $name = "Fred";
php > $sentence = "Your name is {$name}";
php > echo $sentence;
Your name is Fred
If I change the value of $name, the sentence is unchanged:
php > $name = "John";
php > echo $sentence;
Your name is Fred
But I want the sentence to become 'Your name is John'. Is there a way in PHP I can create an iterpolated string that changes when the inner string changes?
No, it not possible the way you want it to working.
Other solutions:
function
function mySentence($name) {
return 'Your name is '. $name;
}
Any other replace string
sprintf('"Your name is %s', $name);
str_replace('{name}', $name, 'Your name is {name}');
Sentence as object
Create class that holds main sentance as ValueObject
class Sentence {
private $sentence;
private $name;
public function __constructor($name, $sentence){
$this->name = $name;
$this->sentence = $sentence;
}
public function changeName($name){
return new Sentence($name, $this->sentence);
}
public function printText() {
return $this->sentence . $this->name;
}
public function __toString(){
return $this->printText();
}
}
Then use simply:
$sentence = new Sentence('Fred', "My name is");
echo $sentence;
// My name is Fred
echo $sentence->changeName('John');
// My name is John
This is of course idea, what options you have to resolve this.
With that, you can add any replaceable placeholders etc.
Expanding on the "Sentence as object" portion of timiTao's answer, here's a more general-purpose "Template string" class you can use as a starting point for things like this.
class TemplateString {
// Usage:
// $t = new TemplateString("Your name is {{name}}");
// $t->name = "John";
// echo $t; // Your name is John
private $template;
private $parameters = [];
public function __construct(string $template, array $defaultparams = null) {
$this->template = $template;
if( $defaultparams) $this->parameters = $defaultparams;
}
public function __set($k,$v) {
$this->parameters[$k] = $v;
}
public function __get($k) {
if( array_key_exists($k,$this->parameters)) {
return $this->parameters[$k];
}
return null;
}
public function __toString() {
$words = $this->parameters;
return preg_replace_callback("/\{\{(\w+)\}\}/",function($m) use ($words) {
if( array_key_exists($m[1],$words)) return $words[$m[1]];
return $m[0];
},$this->template);
}
}
Try it online
What you want to do is not possible in php.
Create a function returning the string.
func getSentence($name) {
return "Your name is $name";
}

how pass parameter to php class by class()::function()

How pass parameter to PHP class by class()::function()?
class greenHouse{
public function __construct(connection $con){
}
public function show(){
}
}
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();
works
$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();
doesn't work
I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?
You are trying to call a function statically with that notation...
$nameclass = 'greenHouse';
$namefunction = 'show';
$class = new $nameclass($con);
$class->$namefunction();
You can instantiate an object and immediately discard it by calling new within braces:
class Test
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function speak()
{
echo $this->name;
}
function __destruct()
{
echo 'dead';
}
}
$class='Test';
$method='speak';
(new $class('David'))->$method();
echo ' is ';
$temp = new $class('John');
$temp->$method();
echo ' is ';
//Daviddead is John is dead
So in your case:
(new $nameclass($con))->$namefunction();

After __toString() no code is working in php

In following code after __toString() the php code is not working why ?
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
echo "Name :".$this->name;
echo "<br> Roll No :".$this->roll_no."<br><br>";
}
function __toString(){
$this->display();
}
}
$std1 = new Student("Bob" , 1);
echo $std1;
$std2 = new Student("John" , 2);
echo $std2;
$std3 = new Student("Tony" , 3);
echo $std3;
$std4 = new Student("Teena" , 4);
echo $std4;
The out put in browser is bellow : Name :Bob
Roll No :1 Rest of the lines are not working;
Try this
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
}
function __toString(){
return $this->display();
}
}
$std1 = new Student("Bob" , 1);
echo $std1;
$std2 = new Student("John" , 2);
echo $std2;
$std3 = new Student("Tony" , 3);
echo $std3;
$std4 = new Student("Teena" , 4);
echo $std4;
Method __toString should return String not call output function. In Your code you done something like echo echo, because inside method display echo is called again. Change __toString to:
return $this->display();
and display method to:
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
This solution fixes Your errors, but You should change display method name to something more matching its current behavior like getString().
Looking at naming conversion ( display method name ) most logical would be such approach:
class Student{
private $name;
private $roll_no;
function __construct($name,$roll_no){
$this->name = $name;
$this->roll_no = $roll_no;
}
public function display(){
echo $this; //conversion to string and echo
}
function __toString(){
return "Name :".$this->name."<br> Roll No :".$this->roll_no."<br><br>";
}
}
So I use inside display method conversion to String by __toString. Current usage would be:
$std1=new Student("Bob" , 1);
$std1.display();
//or the same:
echo $std1; //the same thing like $std1.display();

passing function values to another function in same class

I want to pass function values to another function in the same class, like to store some values in a variable and then call this variable in another function in the same class.
Here is my Code
public function ven_coupon()
{
if ($_POST) {
$number = $_POST['coupon'];
$query = $this->front->ven_coupon($number);
if (count($query) <= 0 ) {
echo "Not Valid";
}
$payment = $this->cart->total();
$dis = $query['discount'];
$name = $query['username'];
$number = $query['number'];
$discount['discount'] = ($payment*$dis)/100;
$discount['data'] = $dis;
$this->load->view('checkout',$discount);
}
}
public function addcart()
{
$ven = $this->ven_coupon();
echo $ven($name);
echo $ven($dis);
echo $ven($number);
}
You could create the fields(variables) you need outside the function then use them using the this keyword. For example:
private $dis;
private $name;
private $number;
public function ven_coupon()
{
if ($_POST) {
$number = $_POST['coupon'];
$query = $this->front->ven_coupon($number);
if (count($query) <= 0 ) {
echo "Not Valid";
}
$payment = $this->cart->total();
$this->dis = $query['discount'];
$this->name = $query['username'];
$this->number = $query['number'];
$discount['discount'] = ($payment*$dis)/100;
$discount['data'] = $dis;
$this->load->view('checkout',$discount);
}
}
public function addcart()
{
$ven = $this->ven_coupon();
echo $this->name;
echo $this->dis;
echo $this->number;
}
Scope of variable is inside the function. You need to made variable as a part of class as:
Basic Example:
class yourClass{
private $name;
public function functionA(){
$this->name = "devpro"; // set property
}
public function functionB(){
self::functionA();
echo $this->name; // call property
}
}
your function ven_coupon() doesn't return anything, therefore $ven is empty when you read it in your function addcart().
in order to pass several variables from one function to another, you need to create an array.
function ven_coupon(){
$dis = $query['discount'];
$name = $query['username'];
$data=array('dis'=>$dis,'name'=>$name)
return $data
}
function addcart()
{
$ven = $this->ven_coupon();
echo $ven['name'];
//etc.
}
Edit: as you are already using an array $query you could simply return $query; in function ven_coupon and then read it in your function addcart()

$_GET and static in PHP

I get for example name=carl from the url in FooStatic and want to initiate the $Name with Carl so I can use it from another function. Can I do that? Or is there some other better way to do that?
class Foo {
private static $Name = "name";
public static function FooStatic(){
if (isset($_GET["name"])){
self::$Name = $_GET["name"];
return true;
} else {
return false;
}
}
I am using the name to get more info from another class
public static function getSomething() {
if (isset($_GET[self::$Name])) {
$name = $_GET[self::$Name];
$ret = $someClass->Foo($name);
return $ret;
}
}
The GET-variables are global, so you can always get them from virtually anywhere (if it is in the same span of the execution) if that's what you are asking.

Categories