Solved

Passing a vabiable to another function

Posted on 2014-02-25
16
229 Views
Last Modified: 2014-03-18
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

0
Comment
Question by:rgranlund
  • 8
  • 4
  • 2
  • +1
16 Comments
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39887593
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

0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39887733
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

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39887742
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!
http://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

0
 
LVL 7

Author Comment

by:rgranlund
ID: 39890194
@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
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39890236
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.
0
 
LVL 30

Accepted Solution

by:
Marco Gasi earned 500 total points
ID: 39890240
As I said above, your code can't work.

function setName($item) requires you pass a parameter to it ($item) but when you call it you don't pass any param so the function setname doesn't get an item whose id set as $name.
Looking at your code, I think you'll need a function getName() instead to call in function doStuff().
In addition you should set a public property $name in your class and never echoing valuyse from within class' methods. Make your functions return values and print them in your page as I show below.

CUSTOM_FUNCTIONS.PHP
<?php
    error_reporting( E_ALL );

class customize      {

public $name;

      function setName($item) {
            $this->name = $item['id'];
      }

      function getName() {
            return $this->name;
      }

}

//  MAIN.PHP
<?php
$custom = new customize();
$custom->setName($item);
echo $custom->getName();
?>
                                           
Anyway, I suggest you to read some book about Php OOP: you can fins a good intro here: http://www.sitepoint.com/books/phppro1/ and a very good advanced traitment here: http://www.apress.com/9781590599099/
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39890243
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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39890248
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).
0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39890250
In the code snippet here, the $item variable is undefined.  PHP error_reporting(E_ALL) should have told you about that, right?
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28374532.html#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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39890296
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

0
 
LVL 7

Author Comment

by:rgranlund
ID: 39890406
@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

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39890505
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.
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39891290
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? :)
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39891711
@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.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39891729
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.
0
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 39891830
@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!
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now