PHP - How to handle method calls - php

Which is the better way to handle the following case? I've been wondering about this for a while and figured I'd ask.
Define a variable?
$getItems = $itemTools->getItems($item_id);
if($getItems)
{
//do stuff
}
Or
if($itemTools->getItems($item_id))
{
//do stuff
}

IMHO it would depend on what you were doing after/within the if branch. If your plan is doing something with the returned data then it makes sense to me storing the results in a var. Otherwise it doesn't.
Looking at the function name I'm assuming it is not a simple check but a function returning 'usable' data so probably you will use this data and you actually need the var.
Unless you are doing this in the global scope, if you are doing this within some method then php will release the memory used by this var once the method ends.
What about doing another (and quick) method named 'hasResults($itemId)' returning a boolean?
Just wondering

Related

How to pass a variable into multiple functions

In my screenshot below you can see I have a list of functions that run a routine, fairly in-depth routine.
Previously, I have ben repeating this routine in multiple classes, but now I would like to consolidate those multiple classes into one class and execute only one function, by passing a variable into that function to determine the output to return.
I know how to pass the variable into "one" function, but how can I pass the variable ($this_id) into my multiple functions below? Basically, whatever $this_id is from get_output($this_id); I want that same variable value to be carried over into the other $this_id functions. See screenshot...
I searched online and all answers I've seen show how to do this in a non static way, but I'm only familiar with calling things statically, really. I tried the obj way, but couldn't get it to work.
Example, execution...
$header = 'CustomTheme_output';
$header::get_output('header');
(please disregard any lose code, the code is what I have so far from trying multiple ways. private $id and __construct are from the online solutions I have been trying)
Could you please clue me in on how I can correctly achieve this? I would be sooo happy to get rid of all the repetitive code, folders and files I have! - Thanks!
Either you pass it directly into each method call:
public function foo($this_id) {
$this->bar($this_id);
}
Or you make it a class attribute, and simply ACCESS it from the various methods:
public function foo($this_id) {
$this->id = $this_id;
$this->bar();
}
public function bar() {
do_something($this->id);
}

Please explain the difference between function($variable) and function()

I have two scripts: the first script receives data via socket and does some stuff with it, the second script holds a function that gets called by the first script. The function happens to make use of a variable created in the first script.
When calling the function from the first script, should I run it like this:
include 'secondscript.php';
//socket stuff, create $variable from input received
functionName()
Or like this:
include 'secondscript.php';
//socket stuff, create $variable from input received
functionName($variable)
I understand that one is a "global" declaration, but I'm having trouble understanding the significance of that. And of course, I'm wondering if that is what's causing something not to work.
Thanks very much.
You really need to read up on the basics of functions.
functionName();
means you are requesting a function and passing no information to it.
functionName($someVar);
means you are sending it the information in the $someVar variable.
Expanding on the above:
The difference is simply the arguments passed. You can access variables through the global declaration within a function, but personally, I think it is a bad idea.
You will always want to know what arguments and types are being passed to and from a function. At least, if you don't want to define the arguments in the function definition, but still pass them as an argument to the function call, you can grab the passed args via something like func_get_args():
// definition
function funca(Array $arr){
// This tells funca to only allow Arrays as the arg type
}
// definition
function funb(){
$args = func_get_args();
// You dont define args, but can still pull them.
}
//call
funcb('a', 'b');

Can a PHP-method detect if it's been called within a loop? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return a loop in function php
To make my question more clear, I'll explain the situation a bit... I'm trying to make a simple yet powerfull PHP-ORM-tool. First versions ( only 25 kB of code ) and tests are quite promising, it has e.g. lazy-loading. Now I'm optimizing the thing by e.g. minimizing the number of queries, ...
For the lazy-loading, I use a Proxy-class. The Child-property of the Parent-class is a Proxy at first. That Proxy contains an empty object...
class Parent {
getChild() { ... }
//other code
}
class Child {
getName() { ... }
//other code
}
class Proxy {
$object = false;
public function _query() { /*some code to get the objects*/ }
__call() {
if(!$objects)
$this->_query();
//perform called function on the $object(s)
}
//other code
}
When we ask the Child from the Parent, we assume it is a Child, but in fact it is a Proxy. As long as we don't do anything with it, we don't have to query the database... Whenever we ask the Child something ( like getName() ), the magic call function comes in action, queries the database an performs the called function on the new object. The principle is easy, but it is a lot more difficult in code... (it also support lists of objects, triggers in loops, has arraysaccess, the querying is quite complex too, ...)
The problem now is the following:
foreach( $parents as $parent ) {
echo $parent->getChild()->getName();
}
Every call in the foreach loop, triggers a query to the database...
I don't want that! Because I already know that I want the children of a list of parents (thats what the human mind says at least...)
Let's assume I have knowledge of all the Proxies of the same type, I would like to do something like this:
class Proxy {
_query() {
## some code to test if the call originates from within a loop ##
//if so: fill all the Proxies of this type with their object(s)
//else fill this Proxy with its object(s)
}
//other code
}
I know I'm simplyfying this a bit, but that's the general idea...
debug_backtrace can give me the method from which a function was called, but I want information on the loop-structures... (if possible even the original list etc...)
Why not just using a parameter like
function _query($loop = false)
when called in a loop you could use _query(true), to tell the function you are in a loop.
Otherwise you could use an internal counter-variable to count the calls for the query. ;)
You can't programmatically, but one hack I can think of is to set a global flag variable before any loop?
You can examine the call stack, but the overhead will be huge.
No, it can't detect that as far as I know but you could always send a parameter when calling the method no?

Object Oriented Design: Return Values or Set Property?

What would be considered "best practice" in this case. I've got a class that's gathering remote resources, and it looks a bit like this:
class Gather {
public function getAll($locations) {
$results = array('All','My','Results');
return $results;
}
}
My question is, would it be considered a best practice to return the results, or to assign them as a property? ie.
// This
$results = $gatherer->getAll();
// vs This
$gatherer->getAll(); // now $gatherer->results can be used
Its quite likely I'm just overthinking this, but I've got no formal training and I'm wondering if there's "more correct" way of doing something like this.
Without question, the first one ($results = $gatherer->getAll()) is preferred. The reason is that the relationship between the value and where it comes from is explicit. In the second case it's not clear to the reader that $gatherer->results is populated by a call to getAll(). Maybe it came from some other call, or it's always there, or set by an outside caller.
This also makes it easier for the reader to trace through to understand the call. When getResults() returns the value it's clear that they reader should read the implementation of getResults() to see where it came from.
I've been wrestling with this same issue lately. In the second version
$gatherer->getAll(); // now $gatherer->results can be used
I would change your naming convention to
$gatherer->initResults();
Then it's obvious that results are a property of $gatherer. You could even define $gatherer->initResults() like so:
public function initResults() {
$this->results = $this->getAll();
}
public function getAll() {
// do whatever to get results
}
So then, you can use either form.
Sorry, I know this is more of a comment then an answer but it was so code heavy it was practically unreadable as a comment.

Documenting implicit input parameters such as $_SESSION

If a function relies on $_SESSION['some_var'] then the header comment out to make that clear. How do you do it? Just as text, or what?
Or even #param?
You could maybe use #uses to document superglobals
Wow, I never even thought about that. I don't even doc things like that. I would say to just state it in the method detail like
/**
* Takes the some_var session variable and uses it to solve world hunger
* #return food
*/
Makes the most sense to me.
There is #global, but that seems to indicate the creation of a global var. I think #param should only refer to method parameters passed to the method. There is no #note, that I know of.
#global has two usages: to denote a global var's definition, and to highlight a global's usage in a method. This second usage fits your use case.
However, assuming that you are referencing $_SESSION['some_var'] directly in that method, and never denoting it via the "global" keyword, it's possible that phpDocumentor's #global tag won't find it when the method is parsed. As such, #uses is probably the best alternative as a means to highlight the method's reliance on that superglobal.
[1] -- http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.global.pkg.html
If your code depends on something global, or external, to be present in order to work (for example, it requires the sqlite to be installed) you can use #use as Nev mentioned.
HOWEVER...
In general, I would say it is a bad practice to have a function populate or use global variables (or use superglobals), as it breaks the encapsulation of the function and creates a strong dependency between the code inside the function and outside.
If any code external to the function is supposed to create or access those globals, the values should instead be passed as parameters to the function.
For example, instead of
function doMagic(){
if ($_SESSION['use_black_magic'] == true){ // var coming from the outside
$_SESSION['magic_results'] = 'dead chicken';
}else{
$_SESSION['magic_results'] = 'unicorn';
}
}
$_SESSION['use_black_magic'] = false;
doMagic();
echo $_SESSION['magic_results']; // (unicorn) variable set within doMagic()
it should be
function doMagic( $use_black_magic = true ){
if ($use_black_magic == true){
return 'dead chicken';
}else{
return 'unicorn';
}
}
$magic_results = doMagic( false );
echo $magic_results; // unicorn
This way, doMagic() doesn't need to know anything about where the results are to be stored, nor where to find the parameter value. And the external code, doesn't need to know that the function doMagic() is doing something with $_SESSION variables.
As soon as your code grows just a little bit, maintaining, sharing, debugging, and extending this kind of code becomes a nightmare...
http://en.wikipedia.org/wiki/Separation_of_concerns

Categories