PHP OOP and Arrays - php

I am new to PHP OOP and I am having problem getting arrays back.
class example
{
public $array;
public function __construct()
{
$this->array = array();
}
public function do_work()
{
$this->array[] = 'test';
}
}
$test = new example();
$test->do_work();
$test->array;
I keep getting a empty array instead of 'test'.
What am I doing wrong?

This is because you never actually call the function $test->do_work(); The constructor just creates the empty array, and then you attempt to access the property. It should be empty.
Updates
I see you updated your question. If you simply echo $test->array, it should just print Array. However, when I copy your updated code and perform a var_dump($test->array), this is the output I get:
array(1) { [0]=> string(4) "test" }
Which I believe is what you are expecting. The code that you have in your question, though, should output nothing. You are doing nothing with $test->array, the variable is being evaluated and then thrown away.

Your last statement, $test->array; doesn't actually do anything. My guess is that you are using something like echo. Your code should output the array if you use for example var_dump, see the example on codepad

Related

unset property in function also affecting passed variable

I have the following code
<?php
$foo[0] = new stdclass();
$foo[0]->foo = 'bar';
$foo[0]->foo2 = 'bar';
destroy_foo($foo);
var_dump ($foo);
function destroy_foo($foo)
{
unset($foo[0]->foo);
}
?>
The output is
array(1) { [0]=> object(stdClass)#1 (1) { ["foo2"]=> string(3) "bar" } }
I would expect $foo[0]->foo to still exist outside the function, but it doesn't. If I remove the properties and just use an array instead, it works. If I change the variable name inside the function, same problem. How can I use properties but make it work as expected?
What you see as an error is a PHP behaviour that's "working as expected": see the objects and references official guide.
It's not clear what you want to achieve with your code, but you should try to pass a clone of your object to the function.
In PHP Objects will only free their resources and trigger their __destruct method when all references are unsetted. So, to achieve your desire result, you have to
assign null insteadof unsetting it.
$foo[0]->foo = null;

Weird PHP Introspection: Get original variable NAMES from function call?

I have a strange question that's probably not possible, but it's worth asking in case there are any PHP internals nerds who know a way to do it. Is there any way to get the variable name from a function call within PHP? It'd be easier to give an example:
function fn($argument) {
echo SOME_MAGIC_FUNCTION();
}
$var1 = "foo";
$var2 = "bar";
fn($var1); // outputs "$var1", not "foo"
fn($var2); // outputs "$var2", not "bar"
Before you say it - yes, I know this would be a terrible idea with no use in production code. However, I'm migrating some old code to new code, and this would allow me to very easily auto-generate the replacement code. Thanks!
debug_backtrace() returns information about the current call stack, including the file and line number of the call to the current function. You could read the current script and parse the line containing the call to find out the variable names of the arguments.
A test script with debug_backtrace:
<?php
function getFirstArgName() {
$calls=debug_backtrace();
$nearest_call=$calls[1];
$lines=explode("\n", file_get_contents($nearest_call["file"]));
$calling_code=$lines[$nearest_call["line"]-1];
$regex="/".$nearest_call["function"]."\\(([^\\)]+)\\)/";
preg_match_all($regex, $calling_code, $matches);
$args=preg_split("/\\s*,\\s*/", $matches[1][0]);
return $args[0];
}
function fn($argument) {
echo getFirstArgName();
}
$var1 = "foo";
$var2 = "bar";
fn($var1);
fn($var2);
?>
Output:
$var1$var2

seems like foreach loop doesnt work

I want to check an object props, but it looks like loop never runs.
$object = $this->helix->Footer();
// var_dump($object) ; // the var dump starts with "object(Helix)#118 (9) { ....."
foreach($object as $prop_name => $prop_val){
echo $object->$prop_name ;
}
Does anyobody have idea what Im doing wrong?
You can use this function also: php.net/get_object_vars
But the issue can be the same. This function can show only the properties it can see.
It means, if you call it outside the class, then only the public vars. But is you call it inside the class, then "everything". (see the comments on the manual page.)

get return value from a function php using oops

I have code below, where i need to get the return value in a variable outside a class and also its print with respective code.
http://codepad.org/mAlhYBll
and below is raw code.
<?php
class test {
public function kk() {
echo "Whats up :";
return "Hello";
}
}
$obj = new test();
$obj->kk();
$abc = $obj->kk();
?>
Now how can i get value returned from a function added an image below
You need to echo $abc. The program is printing something else since you're echoing What's up within the method, remove that.
Exactly as you've done - although you call "kk()" twice, which is not nneeded, so drop line 13.

PHP Convert String to an array or object if it represents one

I have a function that prints information to the page, it does this because it checks if that value exists every time and outputs an error if it doesn't. Due to the unknown nature of what is being sent to this function it always arrives as a string, I can't change this.
Is it possible for this function to interpret strings such as "array[0]" and "object.something" and return that value instead of looking for the value as an index in $this
E.g.
private array = array("stuff");
$this->printValue("string");
$this->printValue("array[0]");
$this->printValue("object.name"); //Some specified object
public function printValue($key) {
if(isset($this->$key)) {
echo $this->$key;
} else {
die($key.' doesn\'t exist');
}
}
Would echo:
string
stuff
thename
Maybe this example helps:
class Example {
public function __construct() {
$this->foo = array(9, 8, 7);
$this->bar = (object) array('attr1' => 'val1', 'attr2' => 'val2');
$this->baz = 'abcde';
}
public function printValue($key) {
echo eval('return $this->' . $key . ';') . "\n";
}
}
$example = new Example();
$example->printValue('foo[0]'); # prints 9
$example->printValue('bar->attr1'); # prints val1
$example->printValue('baz'); # prints abcde
However, take into account that eval poses security risks because it can execute any PHP code and it may cause fatal errors. Using variable variables is safer, though not as general. Anyway, the input of these risky functions must be always validated.
I think the bigger question is, are you trying to use array[0] as an index for something you're trying to reference? I'm assuming so, otherwise you could access the data from those items listed. So, if you ARE wanting to use the array[0] as an index-identifier, then you could do something like:
private data_array['array[0]'] = "stuff";
$this->printValue(data_array['array[0]']);
im not sure but i think you want $pie = print_r($var,true) it sends the string as a return value not printing out

Categories