Loading a class into a function? - php

I`m currently working on a script, and I have the following situation.
function somnicefunction()
{
require 'someexternalclass.php';
$somevar = new SomeExternalClass();
}
For some reason, the above breaks the function. I'm not sure why, I haven't seen much documentation in php.net regarding this, plus google returned no real results.
Does anyone have any idea ?

If you call the function more than once, you may encounter an error by trying to include the same file.
Try using require_once() instead. Other than that, there is nothing inherently 'illegal' about your example.

Your code is absolutely valid. I tested it on localhost and it works just fine. I used following piece of code:
function.php
function loadClass()
{
include_once "include.php";
new SomeExternalClass();
}
loadClass();
include.php
class SomeExternalClass {
public function __construct( ) {
echo "loads...";
}
}
Are you sure you don't have any typo there? If you aren't getting any error, it might indicate that you haven't used the function anywhere.

Try declaring the object first and then pass it as a parameter to the function:
require 'someexternalclass.php';
$somevar = new SomeExternalClass();
function somnicefunction(SomeExternalClass $somevar)
{
// Do function stuff
}

Related

PHP class includes a file, but that file cannot access the class

I have a php class that uses "include" to load some html and php from a file. Within that file I want to access the class object that included the file, but I keep getting "Fatal error: Call to a member function makeSizesSelect() on a non-object ..."
I've tried both include and require, I've tried declaring globals, I've tried everything I can think of and everything I've so far found on SO. Nothing seems to allow the file I include to have php code access the object that included it.
Any ideas?
Here's a few snippets ...
The class file:
class cdf {
public $version = 001;
public function cdf_shortcode( $atts,$content )
{
$this->slog( 2,"shortcode() case: show" );
require( 'templates/container.php' );
}
}
And the required file container.php contains the following (amongst other stuff):
<?php
echo "version = ".$this->version;
?>
I then try to use the object:
$cdf = new cdf();
$cdf->cdf_shortcode( null, null);
The line $this->slog( 2,"shortcode() case: show" ) works. It runs that function (which I haven't included in this snippet) just fine. But then the file I require (or include) cannot use $this to access the object. I'm at a loss. :-(
All I want to do is access within the included file, the variables and methods in the class that included the file ...
Sorry, some added information. I'm not sure if this makes any difference. The code above is all part of a WordPress plugin.
Curious issue with a curious solution. I finally found the answer over here:
Possible to access $this from include()'d file in PHP class?
I tried all the obvious solutions this poster tried (globals, casting to another variable, etc) with the same lack of success. Turns out, just changing the file extension from .php to .tmpl fixed the issue, and my included file can now access the object that included it. Weird. (Of course, the downside now is that my IDE doesn't colour my code for me. :-( )
Thanks for your suggestions guys.
In the file you included you need to instantiate the class.
<?php
$yourClass = new cdf();
echo "version = ".$yourClass->version;
?>
When you want to access a function in a class, you need to instantiate the class first otherwise you wont have access to anything inside of it.
Also make sure the file you are including wont be included anywhere else where the class cdf doesn't exist because that will result in an error.
The variable $this can only access methods, variables, etc. only if they are in the same object.
Update based on your answer that seems to have worked:
Example.php
<?php
echo $this->returnString();
echo $this->randomVariable;
File.php
<?php
class IncludedClass
{
public $randomVariable = 123;
public function returnString()
{
return "some random string";
}
public function meh()
{
require_once('Example.php');
}
}
$meh = new IncludedClass();
$meh->meh();

Using AppUI in Function

I am translating a website and I need to input $AppUI->_('') to make translation in system admin. But, somehow I can't use it in this function.
What am I doing wrong?
Here is my script and I hope you will help me:
public function BeginCalc()
{
if($this->getActive())
{
echo $AppUI->_('Calculating');
}
else
{
$this->_BeginCalculation();
echo "Calculation has been started";
}
}
And, when I use like this I get error Fatal error: Call to a member function _() on a non-object in. Tried to search in Stackowerflow but answers there haven't helped me in solving the problem.
$AppUI does not exists in this scope. If it's global variable, you need to import it with global keyword.
But i'd rather advise you to make $AppUI object a singleton and reference to it by AppUI::getInstance()->_('Calculating');

Fatal error: Class 'Logs' not found in

I'm going crazy over these past few days and I really need your help because I don't know what else to do. I tried everything.
Here is the problem:
I have two files. site.php and logs.php.
Here is the content of logs.php:
class Logs {
function __construct() {
}
}
Now comes the fun part, beginning of 'site.php':
require_once("database.php");
require_once("logs.php");
class Site {
private $db;
private $logs;
function __construct() {
$this->logs = new Logs(); ### this is the error line
$this->db = new MySQLDatabase();
}
}
They are all in the same directory. Why can't it find my class?
PHP might be including the wrong the file. PHP will search the include path before looking inside the script's directory. You may somehow have a logs.php in your include path (See This PHP manual for details.) I suggest maybe adding an echo "hello world"; in the root of your logs.php.
You might also have accidentally enclosed the class inside another class or function. Make sure the class is only inside the tags.
Thank you all for helping. I have found out what the problem was! Turns out, for some reason I shouldn't name my php file 'logs.php'. As soon as I renamed it, it works perfectly. I have no idea why but it just wont work with that name.

Can't use preg_replace inside a static function, why?

Is there any reason why I can't use preg_replace inside a static function? when I move the code out of it, it works perfectly. Any ideas?
Funny, because this works fine:
class obnoxiousWeasel {
public static function callMeDoItIDareYa($omgudid)
{
return preg_replace("/(, you don\'t listen)/", '...', $omgudid);
}
}
$pieceofmymind = "ok, but what's the point, you don't listen";
$reply = obnoxiousWeasel::callMeDoItIDareYa($pieceofmymind);
echo $reply;
returns: "ok, but what's the point..."
We will need to see your code before we can tell you what is wrong. Using preg_replace inside a static function is definitely not the problem.
Edit: I actually edited the above useless function to improve it. Might as well face it, I'm addicted to refactoring.
preg_replace is a core php function and can be used at any scope.
perhaps you are using it to evaluate a class member in the static method? that would not work. but I couldn't say for sure without seeing a relevant chunk of code.

"Fatal error: Cannot redeclare <function>"

I have a function(this is exactly how it appears, from the top of my file):
<?php
//dirname(getcwd());
function generate_salt()
{
$salt = '';
for($i = 0; $i < 19; $i++)
{
$salt .= chr(rand(35, 126));
}
return $salt;
}
...
And for some reason, I keep getting the error:
Fatal error: Cannot redeclare
generate_salt() (previously declared
in
/Applications/MAMP/htdocs/question-air/includes/functions.php:5)
in
/Applications/MAMP/htdocs/question-air/includes/functions.php
on line 13
I cannot figure out why or how such an error could occur. Any ideas?
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
To help with the third point, a solution would be to use include_once instead of include when including your functions.php file -- so it cannot be included more than once.
Solution 1
Don't declare function inside a loop (like foreach, for, while...) ! Declare before them.
Solution 2
You should include that file (wherein that function exists) only once. So,
instead of : include ("functions.php");
use: include_once("functions.php");
Solution 3
If none of above helps, before function declaration, add a check to avoid re-declaration:
if (!function_exists('your_function_name')) {
function your_function_name() {
........
}
}
You can check first whether the name of your function exists or not before you declare the function:
if (!function_exists('generate_salt'))
{
function generate_salt()
{
........
}
}
OR you can change the name of the function to another name.
You're probably including the file functions.php more than once.
In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.
This answer explains why you shouldn't use function inside function.
This might help somebody.
I had strange behavor when my *.php.bak (which automaticly was created by notepad) was included in compilation. After I removed all *.php.bak from folder this error was gone.
Maybe this will be helpful for someone.
Another possible reason for getting that error is that your function has the same name as another PHP built-in function. For example,
function checkdate($date){
$now=strtotime(date('Y-m-d H:i:s'));
$tenYearsAgo=strtotime("-10 years", $now);
$dateToCheck=strtotime($date);
return ($tenYearsAgo > $dateToCheck) ? false : true;
}
echo checkdate('2016-05-12');
where the checkdate function already exists in PHP.
I would like to add my 2 cent experience that might be helpful for many of you.
If you declare a function inside a loop (for, foreach, while), you will face this error message.
I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.
Declare your function as a lambda expression (I haven't seen this solution mentioned):
$generate_salt = function()
{
...
};
And use thusly:
$salt = $generate_salt();
Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.
I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.
require_once is also useful if the file you're attempting to include is essential.
I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')
Since the code you've provided does not explicitly include anything, either it is being incldued twice, or (if the script is the entry point for the code) there must be a auto-prepend set up in the webserver config / php.ini or alternatively you've got a really obscure extension loaded which defines the function.
means you have already created a class with same name.
For Example:
class ExampleReDeclare {}
// some code here
class ExampleReDeclare {}
That second ExampleReDeclare throw the error.
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
I had this pop up recently where a function was being called prior to its definition in the same file, and it didnt have the returned value assigned to a variable. Adding a var for the return value to be assigned to made the error go away.
You have to deactivate the lite version in order to run the PRO version.
This errors says your function is already defined ; which can mean :
you have the same function defined in two files
or you have the same function defined in two places in the same file
or the file in which your function is defined is included two times (so, it seems the function is defined two times)
I think your facing problem at 3rd position the script including this file more than one time.So, you can solve it by using require_once instead of require or include_once instead of include for including your functions.php file -- so it cannot be included more than once.
or you can't create function in loop
such as
for($i=1; $i<5; $i++)
{
function foo()
{
echo 'something';
}
}
foo();
//It will show error regarding redeclaration

Categories