How to pass a variable into multiple functions - php

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);
}

Related

Can I use a function as the name of a function?

I am modifying my PHP framework and trying to figure out an easier way to deal with different request types.
Currently I have this block in a controller method
$methodHandler = self::getMethodHandler(__FUNCTION__);
$this->$methodHandler();
Where getMethodHandler is
protected static function getMethodHandler($function) {
return $function."_".ucwords(strtolower(Request::getMethod()));
}
Ideally I want to reduce that two lines into one but PHP ain't having it
$this->self::getMethodHandler(__FUNCTION__)();
Anyway I could do this?
This should work:
$this->{self::getMethodHandler(__FUNCTION__)}();
That will evaluate self::getMethodHandler(__FUNCTION__) and call the result as a method of $this.

Php global variable range?

update:
the code i put below will be invoked by a form on other webpage. so that's why I didn't made a instance of a obj.
More detail code:
$serverloc='serverURL';
class Aclass{
function push(){
global $serverloc;
echo $serverloc;
funNotinClass();
}
function otherFunction(){
echo $serverloc;
}
}
funNotinClass(){
echo $serverloc;
}
There is a Class contains 2 functiona "push()" and "otherFunction()" and there is independent function "funNotinClass()" and push() calls it. The class is for a web form in other page. When user click submit the form call the class and use the push() function. A weird thing I found is that the global var $serverloc is invisible to push() and funNotinClass()(they don't print out any thing), but otherFuction() which is a function just like puch() inside of the Aclass can just use the $serverloc(I dont even add global in front of it). How strange....anyone know what is the reason caused this?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I read many information about the scope of a global var in php.
they all say a global var is defined outside of function or class and you can use it by using global this key word.
So this is my code
$serverloc='serverURL';
class Aclass{
function Afunction(){
global $serverloc;
echo $serverloc;
}
}
but when I run this class it didn't print anything out.
Is that because I did something wrong or global var just doesn't work this way. Since all the example I read before are just access a global var in functions directly not a function in a class
As per DaveRandom's comment - you haven't actually made an instance of an Aclass object.
This works and displays data as expected:
<?php
$serverloc='serverURL';
class Aclass{
global $serverloc;
function Afunction()
{
echo $serverloc;
}
}
$me = new Aclass();
$me->Afunction(); // output: serverURL
?>
Edit: DaveRandom seems to post asnwers as comments. Go Vote up some of his other answers, the rep belongs to him not me. I am his ghostwriter tonight.
If it is class globals you are after you could do like
class myClass
{
private $globVar = "myvariable";
function myClass()
{
return $this->globVar;
}
}
but when I run this class it didn't print anything out
You don't run classes, in the sense of executing them. A class is a just a data structure that holds data and functions related (called methods).
As most traditional data structures, you create instances of them (called objects), and then you execute actions on them. One way to execute actions on objects (instances of classes), is to pass a message for it to do something: that is calling a method.
So, in your case you could do:
$obj = new Aclass(); // create an object, instance of Aclass
$obj->Afunction(); // ask it to perform an action (call a method)
Having said that, sometimes you want to create a class only for grouping related functions, that never actually really share data within an object. Often they may share data through a global variable (eg.: $_SERVER, $_GET, etc). That may be the case of your design right there.
Such classes can have its methods executed without never instantiating them, like this:
Aclass::Afunction();
While relying on global variables is usually an indicator of quick'n dirty design, there are cases in which it really is the best trade-off. I'd say that a $serverlocation or $baseurl may very well be one of these cases. :)
See more:
The basics on classes and objects in the PHP manual
About the static keyword

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.

Unsetting attributes of dynamic PHP objects

I have a dynamic class referenced by $row->attributes(), that has some overloaded (dynamic) properties, e.g. $row->attributes()->property1.
I want to unset property1. I've tried $row->attributes()->__unset("property1") and unset($row->attributes()->property1). No joy.
Anyone know how to do this?
It's unclear from the question whether you have used this approach, if you have, I'll remove this answer.
Take a look at __unset, simple example is:
class Foo
{
public function __unset($property)
{
unset($this->__my_property_holder[$property]);
}
}
You simply need to do unset($row->attributes()->property1), and it will actually invoke Foo->__unset('property1').

Categories