Call to undefined method. Can't figure out why - php

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.

Related

CodeIgniter problems after upgrading to PHP 7.3

I have upgraded my PHP to version 7.3.4 for my CodeIgniter 3.1.10 installation. After this I noticed that some parts of my website are not working anymore as before (with PHP 5.6) they did.
One of the use cases is when I type in a faulty URL like so:
www.abc.com/nl-be/antwerpen/this-is-a-bad-url
Normally this would go to my 404 page , but right now I first got the following error:
Message: Call to a member function helper() on null
Filename: D:\wamp\www\codeigniter\application\hooks\LanguageLoader.php
The code is:
class LanguageLoader
{
function initialize() {
$ci =& get_instance();
$ci->load->helper('language');
$site_lang = $ci->session->userdata('site_lang');
if ($site_lang) {
$ci->lang->load('message',$ci->session->userdata('site_lang'));
} else {
$ci->lang->load('message',$ci->session->userdata('site_lang'));
}
}
}
I managed to find a work-around to get past this problem using the code below (Is this correct?):
class LanguageLoader
{
function initialize() {
$CI =& get_instance();
if ($CI === null) {
new CI_Controller();
$CI =& get_instance();
}
$CI->load->helper('language');
$site_lang = $CI->session->userdata('site_lang');
if ($site_lang) {
$CI->lang->load('message',$CI->session->userdata('site_lang'));
} else {
$CI->lang->load('message',$CI->session->userdata('site_lang'));
}
}
}
After checking the value of $CI, this time it would not be null, but would be filled in.
At this point after going to the same faulty URL, i am getting the following error message:
Message: call_user_func_array() expects parameter 1 to be a valid callback, class 'Error' does not have a method 'my404'
Filename: core/CodeIgniter.php
The code in CodeIgniter.php at that line contains:
call_user_func_array(array(&$CI, $method), $params);
The error is especially weird, since i have a my404 method in my Error class:
class Error extends My_Controller {
public function my404() {
//Code to show my 404 template
}
}
EDIT: my URL's look like www.<sitename>.com/<languagesegment>/<optionalcityname>/<pathcontroller&function>
If the optionalcityname is filled in in the URL, the entire website is branded in the cities colors and logo etc. If it is left out, the "normal" site appears.
When going to the "normal" site, my 404 page gets shown correctly.
I've never used CodeIgniter but a quick look at the documentation seems to suggest that, inexplicably, they don't use namespaces. This is pretty unheard of for a modern codebase, and you're learning why.
PHP 7.0 introduced the Error class as the base class for all internal PHP errors. Since your code is not namespaced, you're trying to overwrite this built-in class. If you looked at your error log you'd see something like this:
PHP Fatal error: Cannot declare class Error, because the name is already in use in...
Rename your Error class to something that isn't a reserved name and it should get you past this problem.

PHP Methods Referencing Each Other causes PHP to return "No Data"

PHP Methods Referencing Each Other causes PHP to return a page that says "No data received"
I am completly lost as to why this is happening since both methods belong to the same class...help please? : ()
--------- My Code ----- Simplified for Readability ----
<?php
/**
* This is a simplified version of the situation that is causing me problems...
* Each of theses methods needs to make a call to the other method
*/
class SomeClass {
protected static function SomeProtectedStaticMethod() {
SomeClass::SomePublicStaticMethod('some value for the call we make inside the class');
return 'some return value';
}
public static function SomePublicStaticMethod($some_param) {
$some_var = SomeClass::SomeProtectedStaticMethod();
return $some_var . $some_param;
}
}
$var = SomeClass::SomePublicStaticMethod('some value for the call we make outside the class');
?>
I think this should return a Stack Overflow error.
You have generated an endless loop. It will naturally create a fatal error.
The error it generates is:
Fatal error: Maximum function nesting level of '100' reached, aborting!
This will cause an error like this:
Fatal error: Maximum function nesting level of 'xxx' reached, aborting!`
Which is an error similar to StackOverflow because you are recursively calling the methods from each other and stack memory will be overflowed. This is an endless recursive method call (a loop of calling methods from each other that never ends) and should not work this way.
Make sure you have error reporting turned on so you can make sure what's going on. You may put following at the top of your script to turn on error reporting:
ini_set('display_errors',1);
error_reporting(-1);
try replacing SomeClass:: with self:::
public static function SomePublicStaticMethod($some_param) {
$some_var = self::SomeProtectedStaticMethod();
return $some_var . $some_param;
}
but anyway your class is wrong, because your are calling again the public method from the protected, remove this call of the public method
protected static function SomeProtectedStaticMethod() {
return 'hello from protected method';
}

php OOP - call static method from another class within class

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.

PHP Method Disappears?

I am including one PHP script into another using PHP's require_once() method. This script contains a class, TemplateAdmin, which instantiates itself right after the script, like this:
class TemplateAdmin {
// Class body...
}
$templateAdmin = new TemplateAdmin();
This was working fine for a while. However, I have adopted a new importing technique to include classes and packages. I have tested this new technique, and it works! However, for some strange reason, none of the methods in any of the classes I import are there when I need them. However, it seems as though the instance variables are still there.
For example, when a class with this absolute path is called:
require_once("C:\wamp\www\wave_audio\system\server\templates\TemplateAdmin.php");
... I get this error in the call stack:
Fatal error: Call to undefined method stdClass::top() in C:\wamp\www\wave_audio\cms\index.php on line 189
This error is referring to my use of the top() method inside of the TemplateAdmin class.
Does any one have any idea as to why this is happening??? If this helps, I have been using require_once() all along, I am running PHP 5.3.5 on a Windows XP Media Center machine.
Thank you for your time!
Assuming you dont want to use globals here is one way that only requires a few changes.
TemplateAdmin.php:
class TemplateAdmin {
// Class body...
}
return new TemplateAdmin();
Return include once in import:
function import($classes) {
//Convert ECMAScript style directory structures to Unix style
$address = str_replace(".", "/", $classes);
$address = INSTALL_ROOT . "system/server/" . $address . ".php";
if (file_exists($address) && is_file($address)) {
return require_once($address);
} else {
die(""" . $classes . "" does not link to an existing class");
}
}
Assign the variable:
$adminTemplate = import('templates.TemplateAdmin');
I have a feeling your php error message is accurate. I know on your stripped down version, you pieced it together how you're sure it's setup but it's obviously not a direct copy/paste since it's like:
class TemplateAdmin {
public function top() {
//The "top" method...
}
}
So, the error message says that the method "top" is not defined. If it were not including your file properly, it would tell you that the class you instantiated doesn't exist. Either that method does not exist in the class you think it is, or the method has been unset somewhere in that object instance. Trust your error message.

Is there a way to avoid the "redeclared function" fatal error while defining functions within functions in PHP?

I've been implementing a certain plugin (dtabs) on my page in Wordpress but after upgrading to the latest version, I found that I now have an error the 2nd time I call the main function called dtab_list_tabs().
The way it works is, the plugin gets include_once'd but the main function is called however many times you want to place tabs in your layout. I have 2 such calls to dtab_list_tabs().
Now, the problem is, for whatever reason the developer decided to include another function directly inside dtab_list_tabs() called current_tab(). Because it's declared within a function, apparently PHP tries to redeclare it as soon as you call the parent function the 2nd time, which doesn't make any sense to me.
PHP Fatal error: Cannot redeclare current_tab() (previously declared in .../wp-content/plugins/dtabs/dtabs.php:1638) in .../wp-content/plugins/dtabs/dtabs.php on line 1638
The code for that revision is at http://plugins.svn.wordpress.org/!svn/bc/208481/dtabs/trunk/dtabs.php
What I'm trying to figure out is whether there is a way to tell PHP that yeah... it has an internal function, which is a perfectly valid PHP paradigm as far as I know, so don't redeclare it and fail.
As for the situation at hand, I have removed current_tab() as it doesn't appear to be used.
You can use function_exists() to test if a function with that name has already been defined. If you make the definition conditional ( if(something) { function foo() {...} } ) php will "evaluate" the definition only when the condition is met.
function foo() {
if ( !function_exists('bar') ) {
function bar() {
echo 'bar ';
}
}
bar();
}
foo();
foo();
see also: http://docs.php.net/functions.user-defined
(But I'd try to avoid such things all together)
You can wrap your function declaration in an if statement. Use function_exists() to see if the function has been previously declared or not.
if(!function_exists('current_tab')) {
function current_tab() {
myMagicCode();
}
}
You can try this:
if (!function_exists('my_function')) {
function my_function() {
}
}
function_exists() - Return TRUE if the given function has been defined

Categories