how do you define a variable in a class? seems like global only works inside the function.
<?php
$a = '20';
$b = '10';
class test {
global $a; $b;
function add() {
echo $a;
}
}
$answer = new test();
$answer->add();
?php>
i tried this one (use global inside a class but gets error instead)
also, how can you define multiple variables in just 1 line of code instead of defining it each.
To define a class property (or variable), you would do like so:
class Foo {
private $myVar = 'my var'; // define a class property
public function add() {
echo $this->myVar;
}
}
How about passing the data in via the constructor?
Code: (Demo)
$a_outside = '20';
$b_outside = '10';
class test {
public $a_inside;
public $b_inside;
public function __construct($a_passed_in, $b_passed_in)
{
$this->a_inside = $a_passed_in;
$this->b_inside = $b_passed_in;
}
public function add()
{
echo $this->a_inside + $this->b_inside;
}
}
$answer = new test($a_outside, $b_outside);
$answer->add(); // output: 30
Pass the variable to the class via arguments in the constructor call.
Define the values as variables in the class within construct call.
Access the variables within the add() method.
Related
I have a small PHP snippet.
How can I assign a new value to my global from within a main class?
Example:
$GlobalValue = 0;
class SampleModuleController extends SampleController {
public function doSomething() {
$NewValue = 1;
$GlobalValue = $NewValue
}
}
echo $GlobalValue;
//This always echo's 0, When I try to output or print outside the class or use somewhere above in the php code.
//I need to be able to assign the new value from within my class
//and the function doSomething so it should be 1
You can pass parameter as reference in the method doSomething() and then call that function passing your variable $GlobalValue. However it's not very recommended to have global variables. You should consider change your code to more OOP.
$GlobalValue = 0;
class SampleModuleController {
private $newValue = 3;
public function doSomething(&$variable) {
$variable = $this->newValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething($GlobalValue);
echo $GlobalValue; //print 1
If i understood it right what you are trying to do can be achieved quite easily with this:
global $GlobalValue;
$GlobalValue = 0;
class SampleModuleController {
public function doSomething() {
global $GlobalValue;
$NewValue = 1;
$GlobalValue = $NewValue;
}
}
$ModuleController = new SampleModuleController();
$ModuleController->doSomething();
echo $GlobalValue; //print 1
They key is in the "global" keyword (which is the same as accessing the $GLOBAL["your_var_name"] container.
Beside this, as others said relying on global variables should be discouraged.
I just created my first PHP class, but I'm very new to this and now I don't know how to call a variable inside a function that I created.
For example:
class Example
{
public function testFunction() {
$var1 = "Test";
$var2 = "Hello";
}
}
And then, for example, echo $var1.
I know that I can call the function through this:
$something = new Example();
$something->testFunction();
But how can I call one of those variables inside the function?
I also know that if the variable was outside the function, it would be:
$something = new Example();
echo $something->var1;
I could use a return, but that way I would end with just one variable, and I have multiple variables inside that function.
I hope that you can help me.
Variables inside functions aren't available outside them. The function needs to return the variable.
i.e.
function getName(){
return "helion3";
}
echo $myClass->getName();
If you need more than one, return an array:
return array("name1","name2");
To access variables from outside class functions like that, you need to set the variables as properties of the class:
class Example {
public $var1 = '';
private $var3 = ''; // private properties etc are not available outside the class
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
}
}
$something = new Example();
echo $something->var1; // Test
echo $something->var2; // can't do this at all (it's not an object property)
echo $something->var3; // can't do this, it's private!
Of course, you can return whatever you like from the function itself...
public function testFunction() {
$this->var1 = 'Test';
$var2 = 'Test2';
$this->var3 = 'Test3';
return array($this->var1, $var2, $this->var3);
}
You can return private properties and locally scoped variables...
list($var1, $var2, $var3) = $something->testFunction(); // all there!
Variables declared inside your function are only accessible within the function body.
If your function needs to return more than one value, you either a) return a new object, or b) return an array:
return [$var1, $var2];
And in the calling code:
list($a, $b) = $something->testFunction();
Is it possible to :
define('DEFAULT_METHOD', 'defaultMethod');
class Foo
{
public function defaultMethod() { }
}
$foo = new Foo();
$foo->DEFAULT_METHOD();
Or do I have to :
$method = DEFAULT_METHOD;
$foo->$method();
And what about a class constant instead of a define ?
If you use a variable or constant as the method name, you have to put it into curly brackets:
$foo->{DEFAULT_METHOD}();
The same technique works for variables, including static class attributes:
class Foo {
public static $DEFAULT_METHOD = 'defaultMethod';
public function defaultMethod() { echo "Cool!\n"; }
}
$foo = new Foo();
$foo->{FOO::$DEFAULT_METHOD}();
In fact, practically any expression that results in a valid method name could be used:
$foo->{'default'.'Method'}();
You could set it to a variable first as in your example :)
Example: http://codepad.org/69W4dYP1
<?php
define('DEFAULT_METHOD', 'defaultMethod');
class Foo {
public function defaultMethod() { echo 'yay!'; }
}
$foo = new Foo();
$method = DEFAULT_METHOD;
$foo->$method();
?>
Can I change a function or a variable defined in a class, from outside the class, but without using global variables?
this is the class, inside include file #2:
class moo{
function whatever(){
$somestuff = "....";
return $somestuff; // <- is it possible to change this from "include file #1"
}
}
in the main application, this is how the class is used:
include "file1.php";
include "file2.php"; // <- this is where the class above is defined
$what = $moo::whatever()
...
Are you asking about Getters and Setters or Static variables
class moo{
// Declare class variable
public $somestuff = false;
// Declare static class variable, this will be the same for all class
// instances
public static $myStatic = false;
// Setter for class variable
function setSomething($s)
{
$this->somestuff = $s;
return true;
}
// Getter for class variable
function getSomething($s)
{
return $this->somestuff;
}
}
moo::$myStatic = "Bar";
$moo = new moo();
$moo->setSomething("Foo");
// This will echo "Foo";
echo $moo->getSomething();
// This will echo "Bar"
echo moo::$myStatic;
// So will this
echo $moo::$myStatic;
There are several possibilities to achieve your goal. You could write a getMethod and a setMethod in your Class in order to set and get the variable.
class moo{
public $somestuff = 'abcdefg';
function setSomestuff (value) {
$this->somestuff = value;
}
function getSomestuff () {
return $this->somestuff;
}
}
Set it as an instance attribute in the constructor, then have the method return whatever value is in the attribute. That way you can change the value on different instances anywhere you can get a reference to them.
Does anyone know how to reset the instance variables via a class method. Something like this:
class someClass
{
var $var1 = '';
var $var2 = TRUE;
function someMethod()
{
[...]
// this method will alter the class variables
}
function reset()
{
// is it possible to reset all class variables from here?
}
}
$test = new someClass();
$test->someMethod();
echo $test->var1;
$test->reset();
$test->someMethod();
I know I could simply do $test2 = new SomeClass() BUT I am particularly looking for a way to reset the instance (and its variables) via a method.
Is that possible at all???
You can use reflection to achieve this, for instance using get_class_vars:
foreach (get_class_vars(get_class($this)) as $name => $default)
$this -> $name = $default;
This is not entirely robust, it breaks on non-public variables (which get_class_vars does not read) and it will not touch base class variables.
Yes, you could write reset() like:
function reset()
{
$this->var1 = array();
$this->var2 = TRUE;
}
You want to be careful because calling new someClass() will get you an entirely new instance of the class completely unrelated to the original.
this could be easy done;
public function reset()
{
unset($this);
}
Sure, the method itself could assign explicit values to the properties.
public function reset()
{
$this->someString = "original";
$this->someInteger = 0;
}
$this->SetInitialState() from Constructor
Just as another idea, you could have a method that sets the default values itself, and is called from within the constructor. You could then call it at any point later as well.
<?php
class MyClass {
private $var;
function __construct() { $this->setInitialState(); }
function setInitialState() { $this->var = "Hello World"; }
function changeVar($val) { $this->var = $val; }
function showVar() { print $this->var; }
}
$myObj = new MyClass();
$myObj->showVar(); // Show default value
$myObj->changeVar("New Value"); // Changes value
$myObj->showVar(); // Shows new value
$myObj->setInitialState(); // Restores default value
$myObj->showVar(); // Shows restored value
?>