Avoid running function more than once - php

Hi what would be a better way to write the following code so myScript() isn't executed several times?
<?php
function myScript($myVar){
//some code
return $anotherVar;
}
$data = myScript("some input");
echo $data.$data.$data;

$data variable just storing the output its not execute several time when you echo the variable .

In your script the function execute only once. you use the return value more and more.
The function never run alone, it is you who can call for a function to
run.
function myScript($myVar){
return $anotherVar; //5
}
$data = myScript("some input");
echo $data.$data.$data; //555
You can also call this function multiple time if you want different values for different parameter like:
function myScript($myVar){
return $myVar * $myVar;
}
$data1 = myScript(3);
$data2 = myScript(4);
$data3 = myScript(5);
echo $data1." - ".$data2." - ".$data3; //9 - 16 - 25

Related

function definition does't receive the array values using php

I have one function call remove_certificate_packages($certificate_id, array_keys($package_id)) this will invoke the below function
function remove_certificate_packages($certificate_id, $package_id)
{
if (is_numeric($package_id)) // so this is list of package id:s
$package_id = array($package_id);
if (!$package_id) return true;
**notify_package_unlinked($certificate_id,array_keys($package_id));**//one more func call
return true;
}
in this function, I have one more function call "notify_package_unlinked" I need to pass the "$package_id". It will call the appropriate function but the problem is, in the "notify_package_unlinked" function the value is showing "Array". What is the problem? Could you please help
function notify_package_unlinked($certificate_id,$package_id)
{
$query="select id,filename,version from packages where id =$package_id";
$res = db_query($query);
$package= db_fetch_object($res);
$packid=$package->id;
$packname=$package->filename;
$packversion=$package->version;
print "$packid"; // here it is printing the value"Array"
}
I got my output using foreach loop .
foreach($package_id as $id){$pack=$id;}

Is there any way to get the values printed from PHP function without return?

I have basically 2 queries related this:
Consider the following PHP function in a class say xyz.php
function sendResponse(){
$car="Lambo";
echo $car;
}
function sendResponseTwo(){
$car="Lambo";
echo $car;
return $car;
}
function getResponse(){
//case 1:
$carName=$this->sendResponse();
//ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING.
//case 2:
$carName=$this->sendResponseTwo();
//THIS WILL PRINT THE NAME OF CAR
}
In case 1, is there any way to get the echo values by calling the function in another function but without using return statement?
In case2, is there any way to stop the values printed by echo statement (I want only returned value)?
Answer to your both the question lies in output buffer(ob), Hope this will help you out in understanding. Here we are using three function ob_start() will start output buffer and ob_end_clean() will clean the output of buffer and ob_get_contents will give you output as string which is echoed till now. This will help you better understand ob_get_contents
Try this code snippet here
<?php
class x
{
function sendResponse()
{
$car = "Lambo1";
echo $car;
}
function sendResponseTwo()
{
$car = "Lambo2";
echo $car;
return $car;
}
function getResponse()
{
//case 1:
$carName = $this->sendResponse();
//ABOVE WON'T WORK AS THE FUNCTION RETURNS NOTHING.
//case 2:
$carName = $this->sendResponseTwo();
//THIS WILL PRINT THE NAME OF CAR
}
}
ob_start();//this will start output buffer
$obj= new x();
$obj->getResponse();
$string=ob_get_contents();//this will gather complete content of ob and store that in $string
ob_end_clean();//this will clean the output buffer
echo $string;
?>
You need to use output buffering:
ob_start();
$foo->sendResponse();
$response = ob_get_clean();
That's why it isn't a practical design in the first place. If you make the function always return the value it's trivial to do both things to your liking:
$response = $foo->sendResponse();
echo $foo->sendResponse();
<?=$foo->sendResponse()?>
(This last option is shared for illustration purposes and is not intended to open a flame war about short open tags.)

Check if method is false then output results

I have a class that contains a method which carries out various database checks. It then returns the value, if exists.
Here is a very basic setup example:
PHP Class
class myClass{
var $aVar1;
var $aVar2;
function myMethod()
{
// database query
// if results from query return **results**
// else return false
}
}
HTML/PHP File
// setup $myClass object var
<?php if($myClass->myMethod(): ?>
// lots of html
<?php echo $myClass->myMethod() ?>
// lots of html
<?php endif; ?>
This occurance happens multiple times throughout my file with different methods. My question is, I am calling the method initially and checking if it's false and then calling it again to echo the output.
I could do the following but would end up with a variable declaration on every method. There must be a more professional approach?
<?php
$myMethod = $myClass->myMethod();
if($myMethod): ?>
// lots of html
<?php echo $myMethod ?>
// lots of html
<?php endif; ?>
Is there a cleaner more efficient way of doing this?
Age old problem. One common technique is to store the return val in a temporary variable
$result=$myClass->myMethod();
if($result!=FALSE)
echo $result;
You can also use a simpler version
if($result=$myClass->myMethod())
echo $result;
And you can also use the simplest one!
echo $myClass->myMethod() ?: '';
Simpler than the simplest one!
echo $result=$myClass->myMethod();
You can do this to reduce verbosity:
<?php
function foo($bool = true) {
$result = array();
if($bool) {
$result = array('bar');
}
return $result;
}
if(! array()) {
echo 'empty array evaluates to false.';
}
if($result = foo()) {
var_export($result); // Will dump array with 'bar'.
}
if($result = foo(false)) {
var_export($result); // Won't happen.
}
If your return is truish then the contents of the if will execute.

Efficient way to reuse the same call to the same sql table

So I search for this title hoping someone would have already answered it however, I came across similar topics on other languages but not PHP so maybe this will help others.
I am constantly using this following script to call on the database but how can I create it so that I can make it just once at the top of the class for example and use it in every method on the class page that needs it. Example: An single page may not have all of the data it needs from the same table but if the table contains 50% of the data or more for that page, how can I modify this so that I can just say it once and let the rest of the following scripts display the data it extracted in the first place by calling it all just once?
Here's what I have now.
<?php
if($res = $dbConn->query("SELECT Column FROM Table")){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
?>
I want to call on this without the printf(" "); collect and store the data so that I can then call the results while printing or echoing the results with the HTML in other methods. What os the most efficient way? I don't want to make the same call over and over and over... well, you get the point.
Should I use fetch_array or can I still do it with fetch_assoc?
not very sure if it's the answer you want.
you can use include/include_once/require/require_once at the top of the page you want to use the function
for example:
general_function.php:
-----
function generate_form( $dbConn, $sql ) {
if($res = $dbConn->query("SELECT Column FROM Table")) {
while($d = $res->fetch_assoc()) {
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}
and for those pages you want to use the function, just put
include "$PATH/general_function.php";
and call generate_form
Try this:
class QueryStorage {
public static $dbConn = null;
public static $results = [];
public static function setConnection($dbConn) {
self::$dbConn = $dbConn;
}
public static function query($query, $cache = true) {
$result = (array_key_exists($query, self::$results))?
self::$results[$query] : self::$dbConn->query($query);
if($cache) {
self::$results[$query] = $result;
}
return $result;
}
public static function delete($query) {
unset(self::$results[$query]);
}
public function clean() {
self::$results = [];
}
}
usage:
at top somewhere pass connection to class:
QueryStorage::setConnection($dbConn);
query and store it:
$result = QueryStorage::query("SELECT Column FROM Table", true);
if($result){
while($d = $result->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
reuse it everywhere:
$result = QueryStorage::query("SELECT Column FROM Table", true); // it will return same result without querying db second time
Remember: it's runtime cache and will not store result for second script run. for this purposes You can modify current class to make it
work with memcache, redis, apc and etc.
If I understood you correctly, then the trick is to make an associative array and access with its 'key' down the code.
$dataArray = array();
// Add extra column in select query for maintaining uniqness. 'id' or it can be any unique value like username.
if($res = $dbConn->query("SELECT Column,id FROM Table")){
while($d = $res->fetch_assoc()){
$dataArray[$d['id']] = $d['Column'];
}
}
//you have value in the array use like this:
echo $dataArray['requireValueId'];
//or , use 'for-loop' if you want to echo all the values
You need a function which takes in the query as a parameter and returns the result.
Like this:
public function generate_query($sql) {
if($res = $dbConn->query($sql)){
while($d = $res->fetch_assoc()){
printf("Enter HTML here with proper %s", $d['Column']);
}
}
}

How to write short PHP functions that work together

I want to modularize functions, but this is not working...
class Review {
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
private function get_survey($db, $n){
// Query the DB for a certain survey number
if($n == 1){
// Perform some logic
} else {
// Perform some other logic
}
return $a_survey;
}
};
Using the class like this..
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
PHP throws this:
Fatal error: Using $this when not in object context in Review.class.php
Thanks for the help!
Your design pattern is good, you just have a syntax error. You have missed the $ sign on your method calls in show_report(), it should look like this:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
Also, the semicolon at the end of the class is unnecessary.
Finally, as another person mentioned, you need to call show_report with parameters, like this:
echo $r->show_report($db, $id);
Inside your function show_report($db, $id) is the this pointer without the prefixing $ sign which causes the syntax error. Additionally in the second part the function isn't called with parameters.
The function has to look like that:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
echo $r->show_report;
In this example, you are attempting to call the function with no arguments. If this is really what you are doing, that would be at least one problem.
Instead, call the function with arguments:
echo $r->show_report('foo', 1);
Thank you all. I fixed all the syntax errors, thanks to https://stackoverflow.com/a/19258788/1004107. This is the root of the issue I do believe:
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
Should be...
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo $r->show_report($db, $id);
?>
</p>
And this is do to static context? Please comment.

Categories