Name and parameters of parent function - php

I'm trying to figure out how to get the name and parameters of a parent function.
Example:
function foo($a,$b){
bar();
}
function bar(){
// Magic Print
}
foo('hello', 'world');
Output:
foo('hello','world')
Any tips?

You can get the information from debug_backtrace().
function bar(){
$backtrace = debug_backtrace();
$t = $backtrace[1];
print $t["function"] . "('" . implode("','", $t["args"]) . "')\n";
}

Related

function __get() not giving any effect in PHP

So I'm following a tutorial about OOP in PHP and got stuck in understanding how __get() function works. Here's the code:
<?php
class Animal{
protected $name;
protected $favorite_food;
protected $sound;
protected $id;
public static $number_of_animals = 0;
const PI = "3.14159";
//function to return the name
//encapsulation
function getName(){
//when you want to refer attribute in a class
return $this->name;
}
//initialize things
function __construct(){
//generate random 100-10
$this->id = rand(1,10);
echo $this->id ." has been assigned<br/>";
//akses static attribute in a class
Animal::$number_of_animals++;
}
//destruct the object
function __destruct(){
echo $this->name ." is being destroyed :(";
}
//getter : to get protected attribute of a function
function __get($name){
echo "Asked for " . $name . "<br/>";
return $this->$name;
}
//setter : set the attribute to
function __set($name, $value){
switch($name){
case "name" :
$this->name = $value;
break;
case "favorite_food" :
$this->favorite_food = $value;
break;
case "sound" :
$this->sound = $value;
break;
default :
echo $name ."Name not found";
}
echo "Set " .$name. " to " .$value. "<br/>";
}
function run(){
echo $this->name. " runs<br/>";
}
}
class Dog extends Animal{
function run(){
echo $this->name. " runs like crazy<br/>";
}
}
$animal_one = new Animal();
$animal_one->name = " SPOT";
$animal_one->favorite_food = " MEAT";
$animal_one->sound = " RUFF";
echo $animal_one->name ." says". $animal_one->sound. " give me some " .$animal_one->favorite_food. " my id is " .$animal_one->id. " total animal is " .Animal::$number_of_animals. "<br/><br/>";
?>
The output will be like this :
5 has been assigned
Set name to SPOT
Set favorite_food to MEAT
Set sound to RUFF
Asked for name
Asked for sound
Asked for favorite_food
Asked for id
SPOT says RUFF give me some MEAT my id is 5 total animal is 1
SPOT is being destroyed :(
When I try to change the argument and value in __get() function to another attribute like $sound or $favorite_food, it doesn't give any change to the output. The output will still the same. I don't get it why we should set it only to $name.
The name of the parameter inside any function is scoped to that function alone, and doesn't have any reference anywhere else.
You're probably getting confused in that your local function parameter $name has the same name as one of it's class properties $this->name
Notice in your __get method, $name is a stand-in variable for what could be any protected/private property, which is dynamically evaluated at run-time:
$this->$name
as opposed to a hard-coded property
$this->name
Consider this example:
class MyClass {
protected $one = 'first';
protected $name = 'fred';
public function __get(String $property){
return $this->$property;
}
public function getOne(){
return $this->one;
}
public function foo(String $variable_could_be_named_anything){
return $variable_could_be_named_anything;
}
}
$object = new MyClass;
echo $object->one; // first (using __get)
echo $object->getOne(); // first
$object->two = 'second'; // because this property isn't declared protected, accessed normally
echo $object->two; // second
$name = 'jon';
echo $object->name; // fred
echo $object->foo($name); // jon
echo $object->three; // PHP Notice: Undefined property: MyClass::$three
$object->one = 'something'; // Fatal error: Cannot access protected property

Getting a value from a PHP object

I have an object that is returns as below.
print_r($all->getInfo());
//returns the following on browser.
User Object ( [_name:User:private] => Kanye, West [_email:User:private] => kanye#hotmail.com)
I would like to read the name and email and set it to two seperate variables like below.
$email = $all->getInfo()._email;
$name= $all->getInfo()._name;
Any help would be greatly appreciated.
You can do somtething like this to get access to private proprites.
class sampleClass {
private $property1 = 'name';
private $prooerty2 = 'email';
public function getProperty1(){
return $this->property1;
}
public function getProperty2(){
return $this->property2;
}
public function setProperty1($name){
}
$this->property1 = $name;
}
public function setProperty2($email){
$this->property2 = $email;
}
}
To get properties:
$classy = new sampleClass();
echo $classy->getProperty1;
echo $classy->getProperty2;
To set properties:
$classy->setProperty1('name1');
$classy->setProperty2('email2');
You can also use magic methods for __get and __set, more info.
If you want to access the values, you can either set them to public (which may not be the best solution depending on what you're trying to do), or create the __get() magic method
class foo
{
private $value = "foo";
private $value2 = "foo2";
public function __get($name)
{
switch ($name)
{
case "value";
return $this->$name;
default:
return null;
}
}
}
class bar
{
private $value = "bar";
}
$f = new foo;
$b = new bar;
echo "Result:" . $f->value . "<br/>";
echo "Result:" . $f->value2 . "<br/>";
echo "Result:" . $b->value . "<br/>";
this yeilds
Result:foo
Result:
E_ERROR : type 1 -- Cannot access private property bar::$value -- at line 31
Of course, you can also create a function such as get_name() but then you'd have to do that for every private property you want to access.
If you want to control what is and what is not accessible from the __get() method, you can add some logic. This way you know that if you are trying to access a property, it's in the __get() method and not have to try to figure out what the method name is.

PHP: Get the name of the calling function?

Is there a way to get the name of the calling function in PHP?
In the following code I am using the name of the calling function as part of an event name. I would like to modify the getEventName() function so that it can automatically determine the name of the calling method. Is there a php function that does this?
class foo() {
public function bar() {
$eventName = $this->getEventName(__FUNCTION__);
// ... do something with the event name here
}
public function baz() {
$eventName = $this->getEventName(__FUNCTION__);
// ... do something with the event name here
}
protected function getEventName($functionName) {
return get_class($this) . '.' . $functionName;
}
}
Have a look at the output of debug_backtrace().
if you want to know the function that called whatever function you are currently in, you can define something like:
<?php
/**
* Returns the calling function through a backtrace
*/
function get_calling_function() {
// a function x has called a function y which called this
// see stackoverflow.com/questions/190421
$caller = debug_backtrace();
$caller = $caller[2];
$r = $caller['function'] . '()';
if (isset($caller['class'])) {
$r .= ' in ' . $caller['class'];
}
if (isset($caller['object'])) {
$r .= ' (' . get_class($caller['object']) . ')';
}
return $r;
}
?>

get a list of all variables defined outside a class by user

i have something like this:
class foo
{
//code
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
i can get in class foo a list of all variables defined outside by user (newVariable, otherVariable,etc)? Like this:
class foo
{
public function getUserDefined()
{
// code
}
}
$var = new foo();
$var->newVariable = 1; // create foo->newVariable
$var->otherVariable = "hello, im a variable"; //create foo->otherVariable
var_dump($var->getUserDefined()); // returns array ("newVariable","otherVariable");
Thanks!.
Yes, using get_object_vars() and get_class_vars():
class A {
var $hello = 'world';
}
$a = new A();
$a->another = 'variable';
echo var_dump(get_object_vars($a));
echo '<hr />';
// Then, you can strip off default properties using get_class_vars('A');
$b = get_object_vars($a);
$c = get_class_vars('A');
foreach ($b as $key => $value) {
if (!array_key_exists($key,$c)) echo $key . ' => ' . $value . '<br />';
}
What is your goal? Imo it's not very good practice (unless you really know what you are doing). Maybe it's good idea consider create some class property like "$parameters" and then create setter and getter for this and use it in this way:
class foo {
private $variables;
public function addVariable($key, $value) {
$this->variables[$key] = $value;
}
public function getVariable($key) {
return $this->variables[$key];
}
public function hasVariable($key) {
return isset($this->variables[$key]);
}
(...)
}
$var = new foo();
$var->addVariable('newVariable', 1);
$var->addVariable('otherVariable', "hello, im a variable");
And then you can use it whatever you want, for example get defined variable:
$var->getVariable('otherVariable');
To check if some var is already defined:
$var->hasVariable('someVariable')
get_class_vars() http://php.net/manual/en/function.get-class-vars.php
You question is not clear though.
$var->newVariable = 1;
there are two possible contex of above expression
1) you are accessing class public variables.
like
class foo
{
public $foo;
public function method()
{
//code
}
}
$obj_foo = new foo();
$obj_foo->foo = 'class variable';
OR
2) you are defining class variable runtime using _get and _set
class foo
{
public $foo;
public $array = array();
public function method()
{
//code
}
public function __get()
{
//some code
}
public function __set()
{
// some code
}
}
$obj_foo = new foo();
$obj_foo->bar= 'define class variable outside the class';
so in which context your question is talking about?

PHP - member encapsulation returns strange reference

I have a class which has a private member $content. This is wrapped by a get-method:
class ContentHolder
{
private $content;
public function __construct()
{
$this->content = "";
}
public function getContent()
{
return $this->content;
}
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();
Now $foo['c'] is a reference to content, which is what I don't understand. How can I get the value? Thank You in advance.
I just tried your code and $foo['c'] is not a reference to $content. (Assigning a new value to $foo['c'] does not affect $content.)
By default all PHP functions/methods pass arguments by value and return by value. To return by reference you would need to use this syntax for the method definition:
public function &getContent()
{
return $this->content;
}
And this syntax when calling the method:
$foo['c'] = &$c->getContent();
See http://ca.php.net/manual/en/language.references.return.php.
i'm not quite understanding your question. say you changed:
public function __construct() {
$this->content = "test";
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();
print $foo['c']; // prints "test"
print $c->getContent(); // prints "test"
In PHP, you don't say: "$foo = new array();"
Instead, you simply say: "$foo = array();"
I ran your code (PHP 5.2.6) and it seems to work fine. I tested it by dumping the array:
var_dump($foo);
This outputs:
array(1) {
["c"]=>
string(0) ""
}
I can also simple use echo:
echo "foo[c] = '" . $foo['c'] . "'\n";
This outputs:
foo[c] = ''

Categories