I'm trying to cache an Object's method, so every time I call the Class and the method, it won't process again after first time.
Here is what I'm trying to achieve,
class App {
public $data = null;
public function print() {
if ( $this->data === null ) {
$this->data = "First time.";
}
else {
$this->data = "After first time.";
}
return $this->data;
}
}
$data = new App();
echo $data->print() . "<br>";
echo $data->print() . "<br>";
$data2 = new App();
echo $data2->print() . "<br>";
echo $data2->print() . "<br>";
Result
First time.
After first time.
First time.
After first time.
As you can see, it's processing the print() method again when I call it again in $data2.
Is it possible to cache so result will be
First time.
After first time.
After first time.
After first time.
For get your required constant output you need to
change the public variable inside the class to as static variable
Because public static variables share all the available instances of that class each time.
class App {
public static $data = null;
public function print() {
if ( self::$data === null ) {
self::$data = "First time.";
}
else {
self::$data = "After first time.";
}
return self::$data;
}
}
$data = new App();
echo $data->print() . "<br>";
echo $data->print() . "<br>";
$data2 = new App();
echo $data2->print() . "<br>";
echo $data2->print() . "<br>";
Result will be :
First time.
After first time.
After first time.
After first time.
Related
I try to read out a smart contract with web3.php, which works fine now, but I always only can read out a function, that returns a single value. When I call a function that returns for example a uint8 array, then I cannot call the elements of the array with ..[index].
Web3.php: (https://github.com/sc0Vu/web3.php)
That is my callback function:
$contract->at($contractAddress)->call($functionName, function ($err, $result) use ($contract) {
if ($err !== null) {
echo "error";
throw $err;
}
if ($result) {
$supply = $result;
echo $supply;
}
});
Has anyone an idea how I can receive an array in a callback in php?
You can see the answer in the author github "https://github.com/sc0Vu/web3.php".
$newAccount = '';
$web3->personal->newAccount('123456', function ($err, $account) use (&$newAccount) {
if ($err !== null) {
echo 'Error: ' . $err->getMessage();
return;
}
$newAccount = $account;
echo 'New account: ' . $account . PHP_EOL;
});
I am trying to accomplish a simple class method where the user submit its name to a form and it returns a greeting message for every name on the variable array, such as "Welcome John", "Welcome Mike", etc...
Doing this as a regular function is easy:
$arr = array('Mike', 'John', 'Molly', 'Louis');
function Hello($arr) {
if(is_array($arr)) {
foreach($arr as $name) {
echo "Hello $name" . "<br>";
}
} else {
echo "Hello $arr";
}
}
Hello($arr);
However, I can't make it work in class context:
$arr = array('Mike', 'John', 'Molly', 'Louis');
class greetUser {
public $current_user;
function __construct($current_user) {
$this->current_user = $current_user;
}
public function returnInfo() {
if(is_array($this->current_user)) {
foreach($this->current_user as $name) {
echo "Welcome, " . $name;
}
} else {
echo "Welcome, " . $this->current_user;
}
}
}
$b = new greetUser(''.$arr.'');
$b->returnInfo();
replace your $b = new greetUser(''.$arr.''); with $b = new greetUser($arr); and it will work :)
I was commiting a very silly mistake, as users pointed out, I was concatenating the variable when it was not necessary!
So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";
I am trying to learn PHP and stumbled across this problem of having bad keys in my array
i have this function
public function pdf_read_root()
{
$this->root = $this->pdf_resolve_object( $this->c, $this->pdf_find_root());
}
but $this->root is returning the wrong values, how do i get the individual contents, $this->c & $this->pdf_find_root to see what is being used in pdf_resolve_object
public function pdf_read_root()
{
$this->root = $this->pdf_resolve_object( $this->c, $this->pdf_find_root());
echo "<pre>";
echo "<br> Value of member variable c is: ". print_r($this->c, true);
echo "<br> Value of method pdf_find_root() is: ". print_r($this->pdf_find_root(),true);
echo "<br> Value of member variable root is: ". print_r($this->root, true);
echo "</pre>";
}
I am new to PHP and need your help here. I know the basic functionality of this in PHP.
class SwapClass
{
public $num1 = 0;
public $num2 = 0;
function __construct($val1,$val2)
{
echo "In constructor!!" . "<br />";
$num1 = $val1;
$num2 = $val2;
}
public function display()
{
echo "1st value : " . $num1 . "<br />2nd value : " . $num2;
}
}
This is my class. I called it as:
$obj = new SwapClass(2,3);
$obj->display();
The values never come to the display() method. I tried echoing it in the constructor. It's confirmed that values are coming. I then modified the code to:
class SwapClass
{
public $num1 = 0;
public $num2 = 0;
function __construct($val1,$val2)
{
echo "In constructor!!" . "<br />";
$this->num1 = $val1;
$this->num2 = $val2;
}
public function display()
{
echo "1st value : " . $this->num1 . "<br />2nd value : " . $this->num2;
}
}
It works fine now. Why does can't the variables be accessed without this?
Is this used for disambiguation? In my example I have just one object. So what is the problem?
Any member of class is recognized buy using $this in class.
Otherwise it will be treated as local variable where it is being used.
It does not depend on number of object of class, You need to use it for one object as well as for hundreds and more.
http://tournasdimitrios1.wordpress.com/2010/10/11/using-the-keyword-this-in-php/