Jump to content

accessing a variable from procedural through a class


1internet

Recommended Posts

I am trying to access a variable through a class, and can't work out how to this.

class test {

	function method() {
		if (isset({$testing})) {
			echo {$testing};
		}
	}

}

$testing = 'it works';
$thetest = new test;
$thetest->method();

 

Is this even possible, or have I got very confused?

It's both possible, and you're very confused.

 

In PHP, methods and functions are essentially the same thing (notice how they start with the function keyword).  How do you pass a variable to a function?  Through its argument list.  The same thing applies here:

 

 

class test
{
    public function method($x)
    {
        echo $x;
    }
}
 
$testing = 'it works';
$test = new test;
$test->method($testing);

 

EDIT: Note that while methods and functions are essentially the same mechanically, OOP is NOT merely placing a bunch of functions in a class and calling it a day.

Yea, I do, but sometimes I just like to make sure there isn't some standard or much simpler way to do things. It didn't work though.

So I think this is the best way

class test {

	function method($x) {
			echo $x;
	}

}

$thetest = new test;
if (isset($testing)) $thetest->method($testing);


<?php

class Test {
    public $greetings; // Public Variable can be used anywhere

    public function my_world($x) // Global Method
    {
        echo "Good Afternoon, " . $x . "!<br />";
        return $this->greetings = "Have a Great Day " . $x . "!<br />";  // returns a varialble to the calling method
    }

}

$thetest = new Test; // Creat a new instance
$goodbye = $thetest->my_world("Kevin"); // Call the Method
echo $goodbye; //display it.
?>

 

<?php

class Test {
    public $greetings; // Public Variable can be used anywhere

    public function my_world($x) // Global Method
    {
        echo "Good Afternoon, " . $x . "!<br />";
        return $this->greetings = "Have a Great Day " . $x . "!<br />";  // returns a varialble to the calling method
    }

}

$thetest = new Test; // Creat a new instance
$goodbye = $thetest->my_world("Kevin"); // Call the Method
echo $goodbye; //display it.
?>

 

1. Public does not mean global.

2. Methods/functions really shouldn't echo and return.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.