Anoos Sb
Anoos Sb

Reputation: 453

How do I make a variable from outside a function work in that function?

function nothing() { 
    echo $variableThatIWant; 
}

Upvotes: 1

Views: 83

Answers (5)

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

You can also use a class property (or member variable) if you are inside a class:

<?php

$myClass = new MyClass();
echo $myClass->nothing();

class MyClass {

  var $variableThatIWant = "something that I want";

  function nothing() { 
    echo $this->variableThatIWant; 
  }
}

Codepad example

Upvotes: 2

MAMProgr
MAMProgr

Reputation: 410

You can put "global" before the variable you want to use, Like this :

<?php
    $txt = "Hello";
    function Test() {
        global $txt;
        echo $txt;
    }
    Test();
?>

OR : you can passed it as parameter, Like this :

<?php
    $txt = "Hello";
    function Test($txt) {
        echo $txt;
    }
    Test($txt);
?>

source : http://browse-tutorials.com/tutorial/php-global-variables

Upvotes: 4

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41965

You can pass it by reference if you want to modify it inside the function without having to return it:

$a = "hello";
myFunction($a);
$a .= " !!";
echo $a; // will print : hello world !!

function myFunction(&$a) {
  $a .= " world";
}

Codepad example

Upvotes: 1

simshaun
simshaun

Reputation: 21476

The better way is to pass it as an argument.

function nothing($var) {
    echo $var;
}

$foo = 'foo';
nothing($foo);

The evil way, and I dont know why I'm even showing you this, is to use global.

function nothing() {
    global $foo;
    echo $foo;
}

$foo = 'foo';
nothing();

Upvotes: 4

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22172

You have to use global.

$var = 'hello';

function myprint()
{
   global $var;
   echo $var;
}

Upvotes: 3

Related Questions