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
Related
I don't know what is this call system.
For example:
$a = SameClass::fnc1()->fnc2('input')->fnc2();
and we can see this method in jQuery:
$("#selector").parent().css('left',5).fadeOut(1500);
I don't have any idea to write this codes structure in PHP.
You just need to return object from a function
For example
class First
{
public function funcFirst()
{
$obj = new Second;
return $obj;
}
}
class Second
{
public function funcSecond($message)
{
return $message;
}
}
$first = new First;
$message = "Hello";
$result = $first->funcFirst()->funcSecond($message); // 'Hello'
I have this class :
class codici {
public $i;
public $len;
public $str;
public $type;
function __construct()
{
$this->getPad($this->i);
}
public function getPad($i)
{
return ''.str_pad($i,4,'0',0);
}
}
And I use it in this way :
$cod = new codici();
$cod_cliente = $cod->i = 1; //return 1
$cod_cliente = $cod->getPad(1); //return 0001
If I call the class direct, __constructor call internal method getPad and returns wrong answer '1'. Instead, if I call the method getPad return the correct value '0001'.
Why can't I use $cod_cliente=$cod->i=1 ?
$cod_cliente = $cod->i = 1;
It will set value for $cod_cliente and $cod->i both to 1. So when you print $cod_cliente, it will show 1.
But in case $cod_cliente = $cod->getPad(1), code to add padding executes and return 0001.
If you want your constructor to return something you should give it a parameter. And since your getPad($i) returns something you'd need to echo/print the results.
<?php
class codici {
public $i;
public $len;
public $str;
public $type;
function __construct($parameter)
{
$this->i = $parameter;
echo $this->getPad($this->i);
}
public function getPad($i)
{
return ''.str_pad($i,4,'0',0);
}
}
This will allow you to call your class like this:
$c = new codici(3);
which would echo 0003.
this is right code:
class codici {
public $i;
public $len;
public $str;
public $type;
function __construct($parameter)
{
$this->i = $this->getPad($parameter);
}
public function getPad($i)
{
return str_pad($i,4,'0',0);
}
}
now work:
$c= new codici(1);
echo $c->i;//return 0001
echo $c->getPad(1);//return 0001
thank a lot.
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
is there a better way to call an anonymous function inside a class? Here is a simple example that clearifies what I mean.
class foo
{
private $call_back_1 = null;
private $call_back_2 = null;
function __construct($func1, $func2)
{
$this->call_back_1 = func1;
$this->call_back_2 = func2;
}
function provokeCallBacks()
{
//this does not work, and gives an error
$this->call_back_1();
//I would like to avoid this
$method = $this->call_back_2;
$method();
}
}
$call1 = function(){ echo "inside call 1"};
$call2 = function(){ echo "inside call 2"};
$test = new foo(call1, call2);
$test->provokeCallBacks();
* Update 1: Please ignore any syntax error as I have written this on the fly for demo puposes. *
Inside foo:provokeCallBacks, I am trying to call the anonymous functions how ever the first way does not works and gives an error. The second one works but it's a bit stupid that I have to use a temp variable called "$method" to make the call.
I want to know if there exists a better way to call the anonymous function.
call_user_func($this->call_back_1);
No, it's not possible to call an anonymous function via $this.
Another options is;
call_user_func($this->call_back_1);
Being PHP loosely typed, it can't do like {$this -> callback}(); you have to store it in a temp variable or to use call_user_func() either.
EDIT - consider something like this:
class Lambdas
{
protected $double;
protected $triple;
public function __construct($double, $triple)
{
$this -> double = $double;
$this -> triple = $triple;
}
public function __call($name, $arguments)
{
if( is_callable($this -> {$name}) ){
return call_user_func_array($this -> {$name}, $arguments);
}
}
}
$lambdas = new Lambdas(
function($a){ return $a * 2;},
function($a){ return $a * 3;}
);
echo $lambdas -> double(2); // prints 4
echo $lambdas -> triple(2); // prints 6
Dirty and dangerous, but you might succeed using eval..
class foo
{
private $call_back_1 = null;
private $call_back_2 = null;
function __construct($func1, $func2)
{
$this->call_back_1 = func1;
$this->call_back_2 = func2;
}
function provokeCallBacks()
{
eval($this->call_back_1);
eval($this->call_back_2);
}
}
call1 = 'echo "inside call 1"';
call2 = 'echo "inside call 2"';
$test = foo(call1, call2);
$test->provokeCallBacks();
I know your question has been answered but you can try changing your approch ..
class Foo {
private $calls = array();
function __set($key, $value) {
$this->calls[$key] = $value;
}
function __call($name, $arg) {
if (array_key_exists($name, $this->calls)) {
$this->calls[$name]();
}
}
function __all() {
foreach ( $this->calls as $call ) {
$call();
}
}
}
$test = new Foo();
$test->A = function () {
echo "inside call 1";
};
$test->B = function () {
echo "inside call 2";
};
$test->A(); // inside call 1
$test->B(); // inside call 2
$test->__all(); // inside call 1 & inside call 2
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
//....Multiple Items
private $VVal_2000 = 2000; //For Example
private $VNam_2000 = "Two Thousands"; //For Example
private static $Hash = array(); //How to initialize???
private static function Assigning(){
//This function for to assign the array elements (initialize)
global $Hash;
$this->Hash = array(); //to empty Hash variable and not add more data than it should.
$this->Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
$this->Hash[$this->VVal_2000] = $this->VNam_2000;
}
public static function GetVal($Nam) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_search($Nam, $this->Hash))
return array_search($Nam, $this->Hash);
return -1;//error
}
public static function GetNam($Val) {
$this->Assigning(); //or use self::Assigning(); //I want to avoid this call
if (array_key_exists($Val, $this->Hash))
return $this->Hash[$Val];
return "Error";
}
}
Class Testing {
static $OtherVal = Assignation::GetVal("BLABLA"); //for example
static $OtherNam = Assignation::GetNam(20); //for example
//Other functions...
}
Hi, you can see my script or code php...
I need to initialize the Hash array, this have static word because I need to use it in other static function. And this "other function" need to use it for other static variable...
I need to know how to implement it the right way..
Thanks chep.-.
<?php
echo "pre-Class Assignation<br/>";
class Assignation {
private $VVal_1 = 1;
private $VNam_1 = "One";
private $VVal_2K = 2000;
private $VNam_2K = "Two Thousands";
private static $Hash = array();
private static function Assigning(){
if(!empty(self::$Hash)) return;
self::$Hash[$this->VVal_1] = $this->VNam_1;
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}
public static function GetVal($Nam) {
self::Assigning();
if (array_search($Nam, self::$Hash)) return array_search($Nam, self::$Hash);
return -1;//error
}
public static function GetNam($Val) {
self::Assigning();
if (array_key_exists($Val, self::$Hash)) return self::$Hash[$Val];
return "Error";
}
}
echo "post-Class Testing<br/>";
echo Assignation::GetVal("BLABLA");
echo "post-Class Mid<br/>";
echo Assignation::GetNam(20);
echo "post-Class Sample<br/>";
//Testing::MyPrint();
?>
This code is not running, somebody help me testing the code...
result:
pre-Class Assignation
post-Class Assignation
post-Class Testing
that mean:
" echo Assignation::GetVal("BLABLA");"
have error...
In Assigning(), try using self::$Hash rather than $this->Hash and remove the global $Hash. Same applies for calling Assigning(): self::Assigning() as your comments suggest.
$this references the current object, so you must use self:: for all static functions and member data when inside the class.
Also, if this is your real code and not just a sample, you may want to check whether you have already done initialization, otherwise you will be doing it for every call to GetVal() and GetNam(). You could do this by adding something like if(!empty(self::$Hash)) return at the beginning of Assigning()
EDIT
private static function Assigning() {
if(!empty(self::$Hash)) return; // already populated
self::$Hash = array();
self::$Hash[$this->VVal_1] = $this->VNam_1;
//....Multiple Items
self::$Hash[$this->VVal_2K] = $this->VNam_2K;
}