I have the following class to another class in my main class.
class Products
{
public function __get( $key ){
return trim(functions::mssql_escape_string_rev($this->fields[ $key ]));
}
}
This beings back error: Call to undefined method functions::mssql_escape_string_rev()
Is there something wrong with my syntax or can this not be done?
Below is code used to autoload classes, this works for everything else so I know there is nothign wrong with the code. It just doesnt seem to initiate within the class.
// autoloader function called when we try to instantiate a class but haven't included the file
function __autoload($resource_name){
$resource_name = trim($resource_name);
try {
$filepath = CLASS_PATH."/class.".$resource_name.".inc.php";
if(#!include($filepath)){
throw new Exception('');
}
} catch(Exception $e) {
exit("Could not find the required file: ".$resource_name);
}
}
*******EDIT*****
Please ignore this, I made a stupid mistake and included the functions::mssql_escape_string_rev twice. Sorry for timewasting..
As the error says the problem is that functions::mssql_escape_string_rev() is not defined.
Since we can't see what you think is the definition we can not really help you.
For me it looks like the call should be Functions::mysql_escape_string_rev() with capital F and mysql.
Update
Calling static functions from another class works normally: http://codepad.org/wrfm5X7j
Maybe you are calling mysql_escape_string_rev before you included the functions class.
Related
I've been searching for an existing question that already asks this, but I wasn't able to find any questions that quite ask what I'm trying to figure out. The most similar question I could find was this: php 5.3 avoid try/catch duplication nested within foreach loop (code sandwich)
Okay so the place I work at has a web application with a PHP back end. We use an MVC type structure. I'm writing a controller that has multiple methods and in each of my methods I'm wrapping my code with identical try / catch code. In the catch, I pass the exception, a reference to the class, and a reference to the function to a method that builds an error message so that the error messages are formatted the same across the application. It looks something this:
class MyController {
public function methodA() {
try {
// code for methodA
} catch(Exception $e) {
$errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
throw new Exception($errorMessage);
}
}
public function methodB() {
try {
// code for methodB
} catch(Exception $e) {
$errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
throw new Exception($errorMessage);
}
}
public function methodC() {
try {
// code for methodC
} catch(Exception $e) {
$errorMessage = Tasks::buildErrorMessage($e, __CLASS__, __FUNCTION__);
throw new Exception($errorMessage);
}
}
}
So the buildErrorMessage function prevents each method from repeating the code that formats the error message, but there is something that really bothers me about have the same code spread through out every method in the class. I know that PHP doesn't support python-like decorator syntax, but just to demonstrate what I'm envisioning conceptually; I want the code to behave something more like this:
class MyController {
#DefaultErrorHandling()
public function methodA() {
// code for methodB
}
#DefaultErrorHandling()
public function methodB() {
// code for methodB
}
#DefaultErrorHandling()
public function methodC() {
// code for methodC
}
}
Where the #DefaultErrorHandling decorator would wrap each method in that standard try / catch. Is there a way I could achieve this behavior so I don't have to have all of these methods that have repeated code? Or am I thinking about error handling incorrectly?
Thanks to anyone who takes the time to answer this.
Have you looked at a writing a custom exception handler and using set_exception_handler?
What you are doing seems a bit like reinventing the wheel. Does the Exception not already have the info you are collecting in the trace? See: Exception::getTrace
Maybe buildErrorMessage does more? Anyway, I assume a custom exception handler is what you are after.
Not sure if there is a better way to solve this or not, but I created a logging class that formatted the log for me. Then just called this in my catch block.
To log the correct Class and Method, I the debug_backtrace() function. See this answer for more information.
Entry point that calls controller methods can wrap those calls with try / catch. That being said, if you are planning to use different type of error handlers on those methods then you can implement something in your base controller (or use trait) that keeps track of which handler should be invoked on each particular method. Something like
<?php
class MyController extends Controller
{
function __construct()
{
$this->setActionErrorHandler('function_name', 'handler');
}
}
Or just call it at the beginning of action method body. Keeping this type of configuration within class itself will help with readability. Not as neat as python example but better than somewhere in configuration files.
More generic error handlers can be implemented in php by using set_exception_handler mentioned by others.
I'm not really getting why there is such a requirement.
I have read a lot of similar questions and answers but none seems to address my situation.
CLASS A
class A{
public function walk() {
...
}
public function dance() {
require 'dance.php';
}
}
Now inside of dance.php, I have
$this->walk();
And I get this error:
Fatal error: Using $this when not in object context
Please help. Is it that I cannot use $this inside a required file?
Thanks
I have testet it in a clean environment and it works fine for me.
I assume that you maybe include dance.php somewhere else in your code where you are not in object context.
Please take also a look at Possible to access $this from include()'d file in PHP class? which is maybe a duplicate question.
Just tested it, it should work (PHP 5.6).
In my dance.php is just <?php $this->walk(); and the remote method is called. The error must be somewhere else. Looks like you import the file somewhere else where you are not in object context.
Probably you should use traits. Traits enable to build logic and keep them separate to specific classes.
trait dance
{
public function dance()
{
$this->walk();
}
}
class A
{
use dance;
public function walk()
{
echo 'go forward';
}
}
(new A())->dance();
Live example: https://3v4l.org/g1Ybd
I have set up a class with a few functions in it. I've included a seperate php file into the main one. I have a few public functions set up, all which are working. I just went to add a new one, and its throwing an error and I can't figure out why.
if(!class_exists("classBase"))
{
class classBase
{
public function printName()
{
$name = 'Test Name!';
return $name;
}
}
}
I'n my separate file that is included into this one, I am trying to call this function as I am all my other functions in the file.
<?php $this->printName(); ?>
I tried declaring the function before and after the file is included, But for whatever reason, this is throwing the error:
Fatal error: Call to undefined method classBase::printName()
I even tried copying a working function, appending a number to the function name, and calling that new function. But still throwing an error. I'm confused as to why its not working.
You need to initialize an instance of that class. In your example:
if(!class_exists("classBase"))
{
class classBase
{
public function printName()
{
$name = 'Test Name!';
return $name;
}
}
}
$myInstance = new classBase();
$myInstance->printName();
Face Palm
So damn embarassing...
I have two localhost test sites set up. I was editing the class file on the site I wasn't testing, and adding the call to the function into the site I was testing. Therefore it was throwing the error and it was correct, the method was never defined.
Just spent 45 minutes wondering what I was doing wrong...
Clearly I need to step away from the computer and go on lunch.
I am using OpenCart and installed the module sizes.xml, it edits the catalog/product/model/catalog/product.php file
It adds a class method;
I have an issue with some code where in a function I have:
class ModelCatalogProduct extends Model {
public function getSizes($product_id) {
...
} // end function
} // end class
We always get an error saying that we cannot redeclare getSizes method.
I want to either force redeclaration, or alternatively check whether the function exists before calling the method but I cannot use function_exists in a class.
ie, this seems illegal;
class ModelCatalogProduct extends Model {
// This throws up an error
if (function_exists('getSizes')==FALSE) {
public function getSizes($product_id) {
} // end function
}// end if
} // end class
It will throw up an error issue. But I need the function in there.
I would like to use function_exists in this class or alternatively force the method to be redeclared.
How would I make function_exists work inside a class?
You can't have executable code in a class that is outside of a method, so there's no way you can do what you're asking, as your if() condition would need to be in the class body.
So despite what others are saying, method_exists() is not a suitable answer to this question.
If you're getting an error stating that the method is already declared, then there are a few possible reasons for this:
It is actually already declared elsewhere in the same class. In which case, of course you can't redeclare it. But since the code for the class ought to all be in a single file, then it should be fairly easy to see that and avoid doing it.
It's declared in the parent class (ie in your case Model or one of its parents).
Under normal circumstances, you should be able to redeclare a method that is already declared in a parent class; your method would override the method of the same name from the parent class. So for most cases, your whole question is entirely unnecessary.
But you say you're getting errors, so clearly something is going wrong It would help if you'd told us the exact error message, but there are two reasons I can think of this might not work:
If the method in the parent class is declared as Final, then it means the author of the parent class explicitly doesn't want it to be overridden. This means that you cannot have your own method of the same name.
If the method in the parent class has a different signature - eg it's private in the parent but public in your class, or static in one but not in the other, then you will get errors complaining about that. In this case, you'll need to make sure that the methods have the same signature, or else give your method a different name.
Hope that helps.
The answer of #Spudley is correctly chosen as the right answer.
Just more explanation on the first case mentioned in the answer: if you wand to declare the function inside of a method of a class, you should also consider the namespace of the class:
class MyClass
{
function myFunction()
{
//here, check if the function is defined in the root namespace globally
// or in the current namespace:
if(!function_exists('someFunction')
&& !function_exists(__NAMESPACE__ . '\someFunction'))
{
function someFunction()
{
}
}
//....
someFunction();
}
}
If you don't check the second condition of if, calling myFunction() more than once would throw exception
I have a class Logger which, among other things has a method Log.
As Log is the most common use of the Logger instance, I have wired __invoke to call Log
Another class, "Site" contains a member "Log", an instance of Logger.
Why would this work:
$Log = $this->Log;
$Log("Message");
But not this:
$this->Log("Message");
The former fails with "PHP Fatal error: Call to undefined method Site::Log()"
Is this a limitation of the callable object implementation, or am I misunderstanding something?
Unfortunately, this is (still) a limitation of PHP, but it makes sense when you think about it, as a class can contain properties and methods that share names. For example:
<?php
class Test {
public $log;
public function __construct() {
$this->log = function() {
echo 'In Test::log property';
};
}
public function log() {
echo 'In Test::log() method';
}
}
$test = new Test;
$test->log(); // In Test::log() method
call_user_func($test->log); // In Test::log property
?>
If PHP were to allow the syntax you desire, which function would be invoked? Unfortunately, that only leaves us with call_user_func[_array]() (or copying $this->log to another variable and invoking that).
However, it would be nice if the following syntax was acceptable:
<?php
{$test->log}();
?>
But alas, it is not.
Same reasons you can't do this:
$value = $this->getArray()["key"];
or even this
$value = getArray()["key"];
Because PHP syntax doesn't do short hand very well.
This may work:
${this->Log}("Message");
But perhaps it's just easier and better to use the full call? There doesn't seem to be a way to get what you want to work on the one line.
The error in your question indicates it is looking for a function defined on the class which doesn't exist. An invokable object isn't a function, and it seems it can't be treated as one in this case.
as of php7.4 the following code works for me
($this->Log)("Message");