how to change static method in php outside class - php

We can change the static variable value of a class from outside, thats the advantage of static variables but how do we change static method from outside ?
<?php
class A
{
static $static_var = 0;
static function test(){
return 'i want to change inside this test method';
}
}
echo A::$static_var; // outputs 0
++A::$static_var;
echo A::$static_var; // ouputs 1
// Now how do we do something to change the static test method body? is it possible ?
like
A::test() = function(){ /* this is wrong */}
}

As #Mark Baker said, you can only change variable...
But there is a way to declare variable as callable, you can use anonymous function.
here is the documentation: http://php.net/manual/en/functions.anonymous.php
class A
{
public static $method;
}
A::$method = function() {
echo 'A';
};
call_user_func(A::$method);
// OR
$method = A::$method;
$method();

Related

outer variables define inside a class

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.

PHP If Statement in Class to set protected variable

I'm trying to set a class Variable dependent on an if statement in PHP that's available to all the functions in the class. Just setting the variable works fine, but as soon as I attempt to set from an IF statement everything is breaking.
Examples:
Works
class Default_Service_NewSugar {
protected $base_url = "http://url1";
function test() {
return $this->base_url;
}
}
Doesn't work
class Default_Service_NewSugar {
if($_SERVER['APPLICATION_ENV']=="development"){
protected $base_url = "http://url1";
} else {
protected $base_url = "https://url2";
}
function test() {
return $this->base_url;
}
}
Is this not possible in a class? If not is there an alternative way I should be approaching this?
The main problem is that you are putting procedural code inside a class. Referencing to the PHP.net documentation:
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
php.net
I would recommend reading the PHP manual on how to work with OOP, and read many of the OOP tutorials available on the web.
As mentioned in other answers you should do the initializing work inside the class constructor.
class Default_Service_NewSugar
{
protected $base_url;
public function __construct()
{
$this->base_url = ($_SERVER['APPLICATION_ENV'] == "development")
? "http://url1"
: "https://url2";
}
function test()
{
return $this->base_url;
}
}
A more OOP like approach would be to set the URL inside a configuration file and pass the variable to the class when initiating the class.
class Default_Service_NewSugar
{
protected $base_url;
public function __construct($base_url)
{
$this->base_url = $base_url;
}
function test()
{
return $this->base_url;
}
}
//usage would then be:
$default_service = new Default_Service_NewSugar($url_from_configuration_file);
$default_service->test(); //outputs the given URL
You should write that conditional statement inside the constructor. And also, no need to specify the access specifier every time the variable is being initialized, you can specify once and in the initialization part just assign the value. And also optimize your code as well.
class Default_Service_NewSugar {
protected $base_url = "http://url";
function __construct() {
$this->base_url .= $_SERVER['APPLICATION_ENV']=="development" ? 1 : 2;
}
function test() {
return $this->base_url;
}
}
You have lots of typos and that's not the perfect way to work around variables within class
class Default_Service_NewSugar {
protected $base_url;
public function __construct() {
$this->base_url = ($_SERVER['APPLICATION_ENV'] == "development") ? "http://url1" : "http://url2";
}
public function test() {
return $this->base_url;
}
}
As already mentioned, you may initiate your variable inside constructor. Another approach to achieve your goal is to use property access function instead of direct object field access. In this way, you may add additional conditions easily and the code will look like this:
class Default_Service_NewSugar {
public function __construct() {
}
public function getBaseURL($env = null) {
$env = $env ? $_SERVER['APPLICATION_ENV'] : $env;
return ($env == "development") ? "http://url1" : "http://url2";
}
}
$obj = new Default_Service_NewSugar();
print $obj->getBaseURL();

PHP - change class variable/function from outside the class

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.

Reset Class Instance Variables via Method

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
?>

Simple PHP classes question

So I have:
class foo {
public $variable_one;
public $variable_two;
function_A(){
// Do something
$variable_one;
$variable_two;
// If I define variable_3 here!
$variable_3
// Would I be able to access it in function_B?
}
function_B(){
// Do something
$variable_4 = $variable_3
}
}
$myObj = new foo();
// Now what do I write in order to assign "variable_one" and "two" some value?
$myObj->$variable_one = 'some_value' ??
$myObj->$variable_two = 'some_value' ??
First, when you write simply $variable_one; inside A() it does not refer to the member variables of your class! That would be a completely different, newly created local variable called $variable_one bearing no relation to the class variable.
Instead, you want:
function A() {
$this->variable_one;
}
Second, your $variable_3 is also a local variable, and will not be accessible in any other function.
Third, your assignments at the bottom are correct in form, but not in syntax: there's an extra $ in there. You want:
$myObj->variable_one = 'some value';
No, $variable_3 was created (and will be destroyed) in the scope of function_A. This is due to function scope.
http://us3.php.net/manual/en/language.variables.scope.php
If you would like $variable_3 to be retained by your object once execution leaves function_A's scope, you need to assign it as a class property, similar to $variable_1 and $variable2.
class YourClass
{
public $variable_1;
public $variable_2;
public $variable_3;
function_A()
{
$this->variable_3 = "some value"; // assign to the object property
$variable_4 = "another value"; // will be local to this method only
}
function_B()
{
echo $this->variable_3; // Would output "some value"
echo $variable_4; // var does not exist within the scope of function_B
}
}
$myObj->variable_one = aValue;
$myObj->variable_two = anotherValue;
The correct code would be the following (see answer within comments)
class foo {
public $variable_one;
public $variable_two;
private $variable_three; // private because it is only used within the class
function _A(){
// using $this-> because you want to use the value you assigned at the
// bottom of the script. If you do not use $this-> in front of the variable,
// it will be a local variable, which means it will be only available inside
// the current function which in this case is _A
$this->variable_one;
$this->variable_two;
// You need to use $this-> here as well because the variable_3 is used in
// function _B
$this->variable_3;
}
function _B(){
// Do something
$variable_4 = $this->variable_3
}
}
$myObj = new foo();
$myObj->variable_one = 'some_value1'; // Notice no $ in front of the var name
$myObj->variable_two = 'some_value2'; // Notice no $ in front of the var name
Class variables (properties) must be accessed using the $this-> prefix, unless they are static (in your example they aren't). If you do not use the prefix $this-> they will be local variables within the function you define them.
I hope this helps!
If variable_one and variable_two are public, you can assign them as you specified (just remove the "$"...so $classObject->variable_one). Typically you want to encapsulate your variables by making them either protected or private:
class MyClass
{
protected $_variable_one;
public function getVariableOne()
{
return $this->_variable_one;
}
public function setVariableOne($value)
{
$this->_variable_one = $value;
}
}
$c = new MyClass();
$c->setVariableOne("hello!");
echo $c->getVariableOne(); // hello!

Categories