I am rather new to ZendFramework and am trying to figure this out. In my view script (index.phtml), I have this bit of code that says:
<?php
function getErrorString($element)
{
echo "<pre>";
print_r($this);
echo "</pre>";
$string = '';
if(!empty($this->error[$element]))
{
$string = $string.'<label class="error" for="'.$element.'" generated="true">';
foreach($this->error[$element] as $error)
{
$string = $string.$error;
}
$string = $string.'</label>';
}
return $string;
}
echo "<pre>";
print_r($this);
echo "</pre>";
getErrorString("blah");
die();
That gives me:
Fatal error: Using $this when not in object context in index.phtml on line XX
It seems to me that when you create a function within a view, you lose the $this variable. I did search around the net, and I can't see anyone else trying to achieve what I am doing (highly unlikely, maybe I'm searching it wrong).
With past experience developing other apps, I can't see a good reason why this function should be placed in a separate helper -> especially since this is the only place the function will ever be called.
Any ideas would be greatly appreciated.
Your function getErrorString() isn't an objectmethod of the Zend_View-Object.
It has it's own scope and couldn't reach $this.
The following code should work for you in the index.phtml
function getErrorString($viewObject, $element)
{
echo "<pre>";
print_r($viewObject);
echo "</pre>";
$string = '';
if(!empty($viewObject->error[$element]))
{
$string = $string.'<label class="error" for="'.$element.'" generated="true">';
foreach($viewObject->error[$element] as $error)
{
$string = $string.$error;
}
$string = $string.'</label>';
}
return $string;
}
echo "<pre>";
print_r($this);
echo "</pre>";
getErrorString($this,"blah");
die();
The last use of "$this" variable is probably the main reason for showing the fatal error. It's quite justified because of the fact that you cannot write anything else in the class definition, except defining methods & properties with respect to that class.
Also if you are creating any function in a view page, then within that function the "$this" variable is not accessible by default. So you will have to make that "$this" variable go global or you need to print the required part, related to "$this" variable, outside the function definition.
echo "<pre>";
print_r($this);
echo "</pre>";
So when you are writing the above code in the function definition, the PHP Parser is unable to find any object context for this "$this" variable. It's not that you are losing that "$this" variable, but it will not be accessible, but to the missing logic.
Hope it helps.
Related
I'm trying to create a class that enforces its type much like the PHP SplString class.
In this class you can create a string (example from php.net)
$string = new SplString("Testing");
try {
$string = array();
} catch (UnexpectedValueException $uve) {
echo $uve->getMessage() . PHP_EOL;
}
var_dump($string);
echo $string; // Outputs "Testing"
I know PHP is loosely typed however they have got this functionality in SplTypes so I was hoping there might be some way of mimicking this behavior.
I would be expecting to implement it in this kind of fashion below.
public function __assign($value)
{
if($value instanceof MyClass)
{
return true;
}
return false;
}
I'd like to be able to introduce this behavior in my own classes, but cant find the relevant magic method for assignments.
Is this even possible? Or is this a language feature that can't be controlled?
I use internal function function_exists, that can return true but I can't find the custom function in my project. I also debugged my code to trace the function, but the debugger does not step into my custom function. I very look forward to know why. Please help me, thank you.
To find out where is the function defined, use following code:
<?php
$rf = new ReflectionFunction('my_fuction_name');
echo 'file:' . $rf->getFileName() . ', line:' . $rf->getStartLine();
?>
Please note that if the function is not defined in source code, but it's internal PHP function, both getFileName() and getStartLine() will return false.
You can check if the function is internal that way:
<?php
$rf = new ReflectionFunction('my_fuction_name');
if($rf->isInternal() === TRUE){
echo "Function is internal!";
}else{
echo "Function is not internal.";
}
?>
I recently made a class in PHP
I am trying to declare a variable within class and using str_replace in a function but its show undefined variable
class Status{
$words = array(".com",".net",".co.uk",".tk","co.cc");
$replace = " ";
function getRoomName($roomlink)
{
echo str_replace($words,$replace,$roomlink);
}
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");
Any kind of help would be appreciated thanks you
Your variables in the function getRoomname() aren't adressed properly. Your syntax assumes the variables are either declared within the function or passed while calling the function (which they aren't).
To do this within a class, do it while using $this->, like this:
function getRoomName($roomlink)
{
echo str_replace($this->words,$this->replace,$roomlink);
}
For further informations, please have a look into this page of the manual.
Maybe because of the version or something, when I tested your exact code, I got syntax error, unexpected '$words' (T_VARIABLE), expecting function (T_FUNCTION), so setting your variables to private or public should fix this one.
About the undefined varible, you have to use $this-> to access them from your class. Take a look:
class Status{
private $words = array(".com",".net",".co.uk",".tk","co.cc"); // changed
private $replace = " "; // changed
function getRoomName($roomlink){
echo str_replace($this->words, $this->replace, $roomlink); // changed
}
}
$status = new Status;
echo $status->getRoomName("http://darsekarbala.com/azadari/");
Also, since getRoomName isn't returning anything, echoing it doesn't do much. You could just:$status->getRoomName("http://darsekarbala.com/azadari/");.
or change to :
return str_replace($this->words, $this->replace, $roomlink);
I don't like the way var_dump prints out objects. I want to override it with this function:
function var_dump($object, $die = true) {
print '<pre>';
print_r($object);
if ($die) die();
}
I know how to override it in my application, but is there a way to override it globally for all sites on a PHP config level?
You can not do that currently (via "good way") in PHP. And more - you shouldn't.
var_dump() is doing right for what it's intended: plain output and nothing more. If you want to change that, then by definition you want some user-defined behavior. Therefore:
Create your own function. That is what you have now. User-defined functions are for user-defined behavior.
Or else, if you want to do it with var_dump() name by some reason, use namespace like:
namespace Utils;
function var_dump($var, $exit=true, $return=true)
{
$result = sprintf('<pre>%s</pre>', print_r($var, true));
if($exit)
{
echo $result;
exit;
}
if($return)
{
return $result;
}
echo $result;
}
so usage will look like:
$obj = new StdClass();
$str = \Utils\var_dump($obj, false);
//do domething with $str
echo $str; //or use second false
Worst case: runkit_function_redefine() Remember, this is evil. You should not do that because redefining goes against what is function and why it was defined. It is a global side-effect and you should avoid such behavior.
You can use the override_function: http://www.php.net/manual/en/function.override-function.php to replace the behavior of the var_dump function. If you want to include this piece of code in all of your sites, you can put this in your php.ini file:
php_value auto_prepend_file /path/to/file_where_you_override_function.php
The comments indicate that I have to clarify my point: I'm a developer and consultant working on foreign code here. My current assignment is to help migrating an existing (very large) system from PHP4 to Java. While reviewing the code I stumbled across a piece of code that quite confuses me.
Some class (let's call it TestClass) in the system I'm working on does something like this:
function reload(){
$newobject = new TestClass();
$this = $newobject;
}
I gave it a quick try, expecting some inconsistent behavior between accessing members of the object directly or via some getter in case this somehow works. I thought that at worst the external pointers to the existing object and the internal one (aka $this) would target different portions of the heap.
Quick tests seem to indicate that simply nothing happens.
Any idea if this has any (side) effect whatsoever?
Here is my complete test:
<?php
ini_set('display_errors', true);
class TestClass{
var $var1;
function TestClass(){
$this->var1 = 0;
}
function getVar1(){
return $this->var1;
}
function setVar1($value){
$this->var1 = $value;
}
function reload(){
$newobject = new TestClass();
$this = &$newobject;
}
}
echo "<h3>Creating TestObject</h3>";
$testObject = new TestClass();
echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";
echo "Setting member directly to 1<br>";
$testObject->var1 = 1;
echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";
echo "<h3>Calling reload</h3>";
$testObject->reload();
echo "Accessing member directly: " . $testObject->var1 . "<br>";
echo "Accessing member via get: " . $testObject->getVar1() . "<br>";
?>
I expected to get 1 and 0 at last two calls if $this now pointed towards the new object while $testObject would still point to the original one, but 1 is returned in both cases. So I need to know whether the reassignment of $this is doing anything but being a bad idea. If not I can dump that part for good. So if anyone knows of any side effects please tell.
PS: I am fully aware that the above code is not using visibility and such. The original system is written in PHP4 so why bother :-|
Okay, with the hint of a colleague I got it. If the reload function is changed to
function reload(){
$newobject = new TestClass();
$this = $newobject;
}
the object is overwritten with the content of the newly created one. This is due to the copy on write mentioned by "i put on my robe an wizard hat" in the comment above. If used with the forced call-by-reference nothing happens which is good.