Reference or call a function through variable in a php class - php

why can't i assign a function to a variable within a class: e.g
class call {
public $number = function() {
return 3 * 2;
}
}
$num = new call();
$num->number // expecting output 6
Is it possible to assign a method (function) to a property (variable) so that the method can be called outside the class just as a property. e.g
class call {
public $number = $this->value();
private function value() {
return 3 * 2;
}
}
$num = new call();
echo $num->$number // expecting output 6;

Use __get() magic method that called when you trying to get value of inaccessible properties
class call {
public function __get($name) {
if ($name == 'number')
return $this->value();
}
private function value() {
return 3 * 2;
}
}
$num = new call();
echo $num->number;
// 6

Related

How can i use set and get with static private property in php

I would like to keep the value of the static property throught the program, so am using set and get to access a static property.
<?php
class Usuario {
//
private static $usuarioStatico;
//
function getUsuarioStatico() {
return $this->usuarioStatico;
}
function setUsuarioStatico($usuarioStatico) {
$this->usuarioStatico = $usuarioStatico;
}
}
You cannot use $this-> on a static property since it's a reference on the object while $usuarioStatico is a class property.
use self:: instead:
class Usuario {
//
private static $usuarioStatico = 1;
//
function getUsuarioStatico() {
return self::$usuarioStatico;
}
function setUsuarioStatico($usuarioStatico) {
self::$usuarioStatico = $usuarioStatico;
}
}
$u = new Usuario();
echo $u->getUsuarioStatico(); // Output 1
$u->setUsuarioStatico(2);
echo $u->getUsuarioStatico(); // Output 2

Change variable returned as reference from object method PHP

I would like overwrite array element returned as reference. I can do it like this:
$tmp = $this->event_users_details;
$tmp = &$tmp->firstValue("surcharge");
$tmp += $debt_amount;
I would do it in one line like:
$this->event_users_details->firstValue("surcharge") += $debt_amount;
but I get Can't use method return value in write context
Where $this->event_users_details is a object injected in constructor.
My function look like:
public function & firstValue(string $property) {
return $this->first()->{$property};
}
public function first() : EventUserDetails {
return reset($this->users);
}
and users is a private array.
You can't do it without temporary variable stores "surcharge" value.
From documentation:
To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:
<?php
function &returns_reference()
{
return $someref;
}
$newref =& returns_reference();
?>
I checked it with this code:
class Item
{
public $foo = 0;
}
class Container
{
private $arr = [];
public function __construct()
{
$this->arr = [new Item()];
}
public function &firstValue($propNme)
{
return $this->first()->{$propNme};
}
private function first()
{
return reset($this->arr);
}
}
$container = new Container();
var_dump($value = &$container->firstValue('foo')); // 0
$value += 1;
var_dump($container->firstValue('foo')); // 1

Assign property value using an anonymous function

My class is like this:
<?php
class ExampleClass{
private $example_property = false;
public function __construct(){
$this->example_property = function() {
$this->example_property = 1;
return $this->example_property;
};
}
public function get_example_property(){
return $this->example_property;
}
}
$example = new ExampleClass();
echo $example->get_example_property();
Property $example_property must be false until you call it, then, the first time it is called, I want to assign 1 to it. What's wrong with my code?
Error: Error Object of class Closure could not be converted to string on line number 20.
I just tried to play a little bit with your code.
To make it possible, you'll have to find out, whether your variable is a function (defined in your __construct) or the number set by this function
<?php
class ExampleClass{
private $example_property = false;
public function __construct(){
$this->example_property = function() {
$this->example_property = 1;
return $this->example_property;
};
}
public function get_example_property(){
$func = $this->example_property;
if(is_object($func) && get_class($func)=='Closure'){
return $func();
}
return $func;
}
}
$example = new ExampleClass();
echo $example->get_example_property(); //returning 1
echo $example->get_example_property(); //returning 1 again
But anyway, I don't see any sense in doing this.
The typical solution would be something like this:
class ExampleClass{
private $example_property = false;
public function __construct(){
//usually initializing properties goes here.
//$this->example_property = 1;
}
public function get_example_property(){
// I think you want a value to be initialzed only if needed.
// so then it can go here.
if(!$this->example_property) {
$this->example_property = 1; //initialize it, if needed
}
return $this->example_property;
}
}
$example = new ExampleClass();
echo $example->get_example_property(); //returning 1
echo $example->get_example_property(); //returning 1 again

How to pass a chained method as an argument for another method in the same class?

I have a class with a bunch of chained methods. Here is an example:
class Sum {
public static $res = [];
private static $instance = null;
public static function run() {
if (self::$instance === null)
self::$instance = new self;
return self::$instance;
}
public function res() {
return self::$res;
}
public function addTen($int) {
self::$res = $this->addFour($str) + 6;
return $this;
}
public function addFour($int) {
self::$res = $int + 4;
return $this;
}
}
So if I want to call the addTen() method I can do like so:
echo Sum::run()->addFour(5)->res(); // Works, returns 9
echo Sum::run()->addTen(5)->res(); // Doesn't work
The above code doesn't work because the chained methods return the current object from the Sum class. So I managed to fix this by changing the addTen() method so it calls the res() method after the addFour() method like so:
public function addTen($int) {
self::$res = $this->addFour($str)->res() + 6;
return $this;
}
In the above case, that is ok because there is only on method being called from inside the addTen() method but what if I need to call a lot of other chained methods from inside the addTen() method? How can I do so the res() method is no longer needed to be called after every single call from another chained method inside the class (it could become unhandable to have a lot of "->res()" being called everywhere in the class).
I do not know what is your task for this class, but manually writing "add" per function will not make your class adaptable. As I have noted, you have used an array and not chain the $res properly. Since this is a sum class I would expect that you want to sum up the chain.
so I rewrote your class:
<?php
class Sum {
public static $res = [];
private static $instance = null;
public static function run() {
if (self::$instance === null)
self::$instance = new self;
return self::$instance;
}
public function res() {
return array_sum(self::$res);
}
public function add($int) {
self::$res[] = $int;
return $this;
}
}
$sum = new Sum();
$x = $sum->add(5)->add(6)->res();
echo $x; // 11
and you can see it work here:
https://3v4l.org/itDHN

Static Method/Function of Class in PHP

I trying to use static method (I do not want to instantiate a class).
and I put this example.
<?php
class RootClass {
const Member = 20;
public static function Member() {
return self::Member;
}
}
class NewClass {
private $ValNewClass = "";
private function InitNewClass() {
$this->ValNewClass = RootClass::Member();
}
public static function GetNewVal() {
$this->InitNewClass();
$Validation = true;
if ($this->ValNewClass>10){
echo "greater than 10";
$Validation = false;
} else {
echo "Not greater than 10";
}
return $Validation;
}
}
$Val2 = NewClass::GetNewVal(); //It must print "greater than 10"
?>
I need to know where is my mistakes.
This is not real code, only is simple form for ask.
Thank you.
In PHP the $this variable is not available inside a method declared as static.
You can't refer to non-static fields, inside your static method. Values inside this kind of classess cannot be object-dependent. When you use $this->field, you're refering to the value inside an instance of the class. If you want to modify static field, you should use self::field.
<?php
class Rootclass {
const MEMBER = 20;
public static function member() {
return self::MEMBER;
}
}
class Newclass {
private static $valnewclass = "";
private function initnewclass() {
self::$valnewclass = Rootclass::member();
}
public static function getnewval() {
self::initnewclass(); //Initialice Val for make comparation
$validation = true;
if (self::$valnewclass>10){
echo "<br>greater than 10";
$Validation = false;
} else {
echo "<br>Not greater than 10";
}
return $validation;
}
}
$Val2 = Newclass::getnewval(); //It must print "greater than 10"
echo "<br>After";
?>
Thank you
The code is working.
Chepe.

Categories