Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

Passing a vabiable to another function

If I create a function
function functionOne($this) {
$id = $this['id'];
return $id;
}

Open in new window


How do I pass that variable to another function?
function functionTwo() {
$id =  functionOne();
echo $id;
}

Open in new window

Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Your code is right, except that functionOne expects to get the parameter $this, so when you call it you must pass it that parameter:

function functionTwo() {
$id =  functionOne($some_this);
echo $id;
}
                                  

Open in new window

Or like this if the $value is coming from outside both functions.
function functionTwo($value) {
$id =  functionOne($value);
echo $id;
}

functionTwo("MyID");

Open in new window

Please avoid the use of $this in any context other than PHP object-oriented programming.  It's a sure way to guarantee that you've written confusing code!

The basics of variables and parameters, as passed between functions, is a fundamental part of PHP.  Please, please go through the introductory materials!
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

Example: http://www.iconoun.com/demo/temp_rgranlund.php

<?php // demo/temp_rgranlund.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28374532.html


/**
 * ALL THIS FUNCTION DOES IS ACCESS THE ARGUMENT (PARAMETER) VARIABLE
 * WHICH IS ASSUMED TO BE AN ARRAY.  THE FUNCTION GETS THE VALUE FROM
 * THE 'id' POSITION OF THE ARRAY AND RETURNS IT TO THE CALLER
 */
function functionOne($x) {
    $id = $x['id'];
    return $id;
}
                                  

// How do I pass that variable to another function?

/**
 * THIS FUNCTION PASSES THE ARGUMENT (PARAMETER) VARIABLE WHICH IS
 * ASSUMED TO BE AN ARRAY INTO THE FunctionOne() FUNCTION.  IT GETS
 * THE RESULT BACK FROM FunctionOne() AND WRITES IT TO THE BROWSER 
 * OUTPUT STREAM
 */
function functionTwo($y) {
    $id =  functionOne($y);
    echo $id;
}

// SET UP THE TEST DATA
$thing = array();
$thing['id'] = 'Hello';

// CALL THE FUNCTION #TWO THAT IN TURN CALLS FUNCTION #ONE
FunctionTwo($thing);

Open in new window

Avatar of Robert Granlund

ASKER

@ALL:
I need to clarify my question.  As I better understand, the better my ability to ask the question.

I have two functions within a Class.
CUSTOM_FUNCTIONS.PHP
<?php
    error_reporting( E_ALL );

class customize	{
	function setName($item) {
		$name = $item['id'];
		return $name;
	}

	function doStuff()	{
		$name = $this->setName();
		echo $name;
	}
}

//  MAIN.PHP
<?php 
$custom = new customize();
$custom->setName($item);
$custom->doStuff();
?>

Open in new window


This first function $custom->setName($item); is getting a value from another source.  I want to use that value else where in my class but I can't seem to pass it around.
When I run what is above I get the error:
Warning: Missing argument 1 for customize::doStuff(), called in main.php on line 51 and defined in custom-functions.php on line 12
Ahh, the functions are within a class, making them class methods (a term of art in object oriented programming).  I'll reread the question and see what has changed.
ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The 'doStuff' function doesn't receive anything and doesn't pass anything when it calls 'setName'.  Nuthin is Nuthin.  

I think you probably need a static variable somewhere in your class where you can store data while your program runs.  '$name' in both cases is just a 'local' variable for the functions.  It's not even shared between them.
I want to use that value else where in my class but I can't seem to pass it around.
There are two ways to pass variables around inside a class (and class extensions).  One way is to pass the variable as an argument in the function call statements.  The other way is to use $this-> as a prefix to the variable name, thus making the variable into a class property (a term of art in object oriented programming).
In the code snippet here, the $item variable is undefined.  PHP error_reporting(E_ALL) should have told you about that, right?
https://www.experts-exchange.com/questions/28374532/Passing-a-vabiable-to-another-function.html?anchorAnswerId=39890194#a39890194

Also, this does not make sense, given the line numbers in the code snippet.
Missing argument 1 for customize::doStuff(), called in main.php on line 51 and defined in custom-functions.php on line 12
One of the concepts that I have found enormously valuable as I try to learn any programming language is the SSCCE.  You might consider using that when you set up code snippets to post here at EE.  If I can copy your code snippet and run it on my server, I have a great head start on helping you get a good answer.
Here is the new version.  Follow the variables through the code and see if it makes sense to you now.
http://www.iconoun.com/demo/temp_rgranlund.php

<?php // demo/temp_rgranlund.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28374532.html


class customize
{
    /**
     * A NULL CONSTRUCTOR
     */
    public function __construct() {}

    /**
     * A METHOD THAT TAKES AN ARRAY AND RETURNS THE VALUE OF THE 'id' POSITION
     */
    public function setName(array $item)
    {
        // COPY THE ARRAY ELEMENT INTO A NEW VARIABLE
        $name = $item['id'];

        // RETURN THE NEW VARIABLE
        return $name;
    }

    /**
     * A METHOD THAT CALLS ANOTHER METHOD AND ECHOS THE RETURN VALUE
     */
    public function doStuff($x)
    {
        // CALL A CLASS METHOD TO GET THE ARRAY ELEMENT OUT OF THE INPUT ARG
        $name = $this->setName($x);

        // WRITE THE ARRAY ELEMENT TO THE BROWSER
        echo $name;
    }
}


// SET UP THE TEST DATA
$thing = array();
$thing['id'] = 'Hello';

// USE THE CODE
$custom = new customize();
$custom->doStuff($thing);

Open in new window

@Ray, you have me a little confused
@Marco, that got me very close to what I need:
More information that will help me understand.
   error_reporting( E_ALL );

class customize      {
public $name;

      function setName($item) {
            $this->name = $item['id'];
      }
//  This function is run on a page within a foreach statement:  It has three returns, Rob Bob and Robert

      function getName() {
            return $this->name;
      }
//  This function runs on another page, outside of a foreach statement.  I would like it show all of the three names.
}

PageOne.php
<?php
$custom = new customize();
$custom->setName($item);
?>

PageTwo.php
<?php
$custom = new customize();
echo $custom->getName();
?>

So far, I can't get the Page two to work.  Sorry for the confusion, I'm trying to muddle my way though this and I find it very confusing.  But I'm sure the light bulb will go off soon.

Open in new window

Whoa!!

A new, previously unknown, surprise suddenly emerges -- these class methods are being called on two different web pages??!

Are there any other secrets you're keeping from us?  This is like playing whack-a-mole.

Rather than be confused, here is what I recommend you try.  See if there is a community college in your area that teaches PHP.  Sign up for a class in object-oriented programming.  You can have a daily dialog with an instructor, and that will be a much faster path to knowledge than trying to ask questions piecemeal in an online forum like EE.

An alternative might be to start with the PHP OOP documentation and meticulously work your way through it, setting up test cases and exercising your knowledge step by step.  The starting link is here:
http://php.net/manual/en/language.oop5.php

If you do that, and if create the SSCCE for each example you're trying to grok, and if you you post the links and source code for your work, we can almost certainly be helpful.  But in this question I feel like it's been a waste of your time because I don't have any idea about the essential nature of your questions -- there are so many vital elements that are omitted from the online dialog, and they are unfolding in a bit-by-bit manner.  My wife calls this "cutting off the dog's tail one inch at a time."

Learning object-oriented design and programming is not a one month exercise.  It's a semester of concentrated college study with daily, intensive practice.  Don't hurry yourself at the expense of a good understanding; this is one of the most important innovations in software development of the last 20 years!

Here is what I recommend that you try now.  Show us the test data.  Do not show us any programming that does not work.  Instead just show us the inputs you have and and the outputs that you want.  Armed with that information we may be able to show you the program code that will help bridge the gap.
Keep in mind class doesn't provide any automatic storage mechanism. If you need to pass class properties' values through your application pages you must provide a storage mechanism by yourself: you can use serialize function, $_SESSION global array, a database or a text file, but you must do it your self.

Anyway, I agree with Ray: it seems you're proceeding without a clear project in mind and this is a bad idea with procedural scripts but a really impossible programming style in OOP. You have to decide exactly what you need to do, how many classes you need to accomplish the task and what class must exactly do and how. OOP requires a carefull planning  job before to start to write code and it requires you have at least a first knowledge of all basic aspects of OOP programming style, its advantages and its features and even its disadvantages - since not always it's recommendable to use OOP.

Read at least the first book I suggested above or find another one by yourself.
If you can, do what Ray said: post here what is your input and what is the desired output. It seems you want offer to your user a way to customize their personal profile on your site: if so, I would find a class 'user' more useful than a class 'cutomize'. Keep in mind a class is the abstract representation of an object which does actions not of the action itself: a user can changes his data through one or more methods.

@Ray: I saw we're missing a good article (maybe a series of articles) introducing to oop in Php: can this sound interesting? :)
@MarqusG: These from @gr8gonzo look good to me.  But the only reason I can find them is because I already know about them!

Beginning OOP and Advanced OOP

FWIW, I am on the EE Product Advisory Committee.  The ability to search the web site effectively is one of the central issues EE will be trying to address in 2014.
Also, regarding Serialize and PHP sessions, there is a potential gotcha.
http://php.net/manual/en/function.unserialize.php#112823

For this reason and the security risk (see man page Warning) that unserialize() can cause code to run in, eg, a class constructor, I have been getting away from serialized data and using JSON strings instead.
@Ray: wonderful, thanks for the links: I'll suggest them as start point.
Effectively I no more use search function in EE after some failed experiment: good luck with that project!