-1

I m searching for some help

It is possible to set a function with Arguments/Parameters inside another function in php? Here i have a theoretical example.

<?php

// Function with parameter/s
function funcOne($arg) {
    return $arg;
}

// Parameter/s inside another function.. Possible!?
function funcTwo() {
    return funcOne($arg);
}

When i try to set the parameter like this

funcOne('Alex');
echo funcTwo();

I get the following notice error

Notice: Undefined variable: arg in...

Thanks in advance :)

Anass
  • 59
  • 2
  • 8
  • You just need to call the second function, but the function also needs to get the parameter to call the first function with it. – Rizier123 Jul 01 '16 at 21:25
  • funcTwo() does not know about $arg, it is not in it's variable scope, not visible to is. – PaulH Jul 01 '16 at 21:27
  • Thanks @Rizier123 for your answer. That solve my doubt. :) – Anass Jul 01 '16 at 21:28
  • Gave you a detailed answer for your understanding. Use object oriented concept. Follow more about the scope of variables – Dharam Jul 01 '16 at 21:30

3 Answers3

1
// Function with parameter/s
function funcOne($arg) {
    return $arg;
}

// Parameter/s inside another function.. Possible!?
function funcTwo() {
    return funcOne($arg);
}

funcOne('Alex');
//Call is made to function one which returned an ARG.

NOTE that here the function just returned the arg and forgot about it, now that argument is NO WHERE stored to be used

//Now here inside the functionTwo scope $arg is never defined.
echo funcTwo();

You may do the following using classes and objects

class MyClass {

    public $classarg;

    public function funcOne($arg) {
        $this->classarg = $arg; //assigned the argument to a class variable
    }

    function funcTwo() {
        return $this->classarg; //using the class variable to test
    }

}

$myobj = new MyClass();
$myobj->funcOne('Alex');
echo $myobj->funcTwo()

You can also use global variable to achieve what you want, but I will NOT recommend to use it as Object Oriented Programming is what we should be using going forward

Dharam
  • 423
  • 2
  • 10
1

funcOne('Alex')is not setting a parameter, it is calling the function funcOne(). When funcOne($arg) executes, it returns the parameter $arg to the caller. echo funcOne('Alex') will echo Alex, because that is the value returned. After return, funcOne does not know about 'Alex' any more.

when you call funcTwo(), it executes funcOne($arg), but $arg is not defined: it has no value assigned.

PaulH
  • 2,918
  • 2
  • 15
  • 31
-1
function funcTwo($arg) {
    return funcOne($arg);
}

Note that you should learn to use variables before making functions.

Julie Pelletier
  • 1,740
  • 1
  • 10
  • 18