This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
Before I ask about problem, I read the suggested link, but it didn't help me.
My problem is when I try to instance a class.
The error is:
Notice: Undefined variable: userCore in
/Applications/MAMP/htdocs/proyecto_cice/app/web/controller/controllerFormUser.php
on line 74
I know the meaning of this notice, so I use the function class_exists() and I give me true. I used this function, because my first idea was I make a mistake in the class, but it isn't the problem.
I declare this object in load.php file, because I need it in others files too.
I understand the error, but I don't find it. If you can help, I'll be grateful.
The code in the main file where I try instance the class:
<?php
require '../load.php';
function signup($form){
if( $form['pass']== $form['repass'] ){
$exists = $userCore->find_mail( filter_project_form() );
if($exists==''){
$isCorrect = ($userCore->insert_user( filter_project_form() ));
if($isCorrect){echo 'correct';}
}
else{
echo "The user exists now";
}
}
else{
echo 'The passwords must be identical';
}
}
?>
And the file 'load.php' contains:
<?php
//CONFIG
require 'config.php';
require 'constants.php';
//CORE
require 'core/ddbb.php';
require 'core/user.php';
</code>
//CLASS MODEL
require 'model/class_user.php';
//CONTROLLER
require 'controller/controllerUser.php';
//INSTANCIA
$userCore = new User_core();
And the file core/user.php is:
<?php
class User_core extends DDBB_core{
function find_mail($form){
$sql = "SELECT email FROM user WHERE email='".$form['mail']."'";
return $this->executeSelectQuery($sql);
}
}
Thanks
The variable $userCore is not available in your function, as it is defined in the outer scope. You need to make it available:
[...]
function signup($form){
global $userCore;
[...]
By the way, doing things like this is considered bad practice and it goes against the OOP principles. It would be better if you made siginup a method of the UserCore class, or used some kind of rendering utility class for this, where you instead pass the instance of UserCore as one of the arguments to the function instead.
Related
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();
[SOLVED]: I've set a SESSION variable that I can use in the whole project ;)
I already took a look at the variable scope argument on the php manual online,but still I couldn't find a solution to my problem :(
In my controller I've got the following:
if(isset($_POST["idMappaMod"])){//Modifica mappa
$oldmap=$this->model->ottieniindirizzo($_POST["idMappaMod"]);
include'view/modmap.php';
}
After the click on the NewMapAddress button,I want to manage that (again in the controller):
if (isset($_POST["NewMapAdress"])){
$result_map_mod=$this->model->modificamappa($oldmap,$this->user->id,$_POST["NewMapAdress"]);
include'view/modmap.php';
}
I get the undefined variable notice on the $oldmap variable. How can I do? Already tried to declare it outside everythin as global. Did not help.
What about you create a public variable into your class? So you could manage this variable through your instaced class, something like this:
<?php
class YourClass {
public $old;
public function yourFunction() {
$this->old = ...
}
}
$yourClass = new YourClass();
$yourClass->old; // here you have the variable from the instance
?>
This question already has an answer here:
Is there a way to disable adding properties into a class from an instance of the class?
(1 answer)
Closed 8 years ago.
I have the following case.
I have a class without variables, which by mistake sets a value to a variable that 'does not exists', in its constructor. The outcome is that the variable is created on the fly and it is viable as long as the class instance exists.
myClass.php
class myClass {
public function __construct($var)
{
$this->var = $var;
}
public function printVar() {
echo $this->var. "</br>";
}
}
tester.php
include("myClass.php");
$myClass = new myClass("variable");
$myClass->printVar();
var_dump($myClass);
And when I run the tester.php the output is the following
variable
object(myClass)#1 (1) { ["var"]=> string(8) "variable" }
Does anyone knows why this is happening? Can you point me to any documentation lemma that explains this behavior?
Is it possible to avoid something like this overloading the __set() function?
It is because php don't make it mandatory to declare before assigning value to it. But you should always declare variable in class as it increases readability of your code and also you can specify accessibility of variable to be public or private.
If you are looking at creating vars on the fly based on a string you pass, you might want to check on $$vars, yes, two time '$' if i got your problem correctly this time
This question already has answers here:
Is it possible to overwrite a function in PHP
(10 answers)
Closed 9 years ago.
I have a main php file in the root which is included by several others on different directories ,I don't want to allow few functions written in main files to execute if included by another file.
I ran an test code and tried overwriting an function by re-declaring it on including but it returned an error:
a.php
<?php
function show(){echo "a";}//This is what I want to over-ride with
include 'b.php';
b.php
<?php
function show(){echo "b";}//This is the function i want to restrict.
show();
Fatal error: Cannot redeclare abc() (previously declared in C:\xampp\htdocs\abc.php:3) in C:\xampp\htdocs\xyz.php on line xx.
You can do this with anonymous functions (PHP5.3)
$show = function(){
echo "a";
};
$show = function(){
echo "b";
};
$show();
Will now echo "b".
You can't redeclare a function. You need to use unique names for each function.
The functions won't execute just because you include the file they're in. That is unless you're actively calling them inside the file.
I'd suggest evaluating the way you include files to resolve your issue. You may also want to look into include_once / require_once and the function_exists conditional.
E.g.
if ( ! function_exists( 'my_function' ) ) :
function my_function() {
}
endif;
The best way to do this would be to use PHP's OOP features, which allow you to specify visibility of methods.
You can check within a function if the "main file" is included or not, try something like this:
function someFunction() {
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
echo "Not included.";
} else {
echo "Included. No access.";
}
}
Or place the condition "outside" the function(s) definition, so it won't be defined if you include that file.
But I would go with an OOP approach.
I'm getting an error, the full error is:
Fatal error: authnet_cart_process() [<a href='function.authnet-cart-process'>function.authnet-cart-process</a>]: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "AuthnetCart" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in /home/golfetc/public_html/wp-content/plugins/sccp-2.4.0/authnet_functions.php on line 1266
I'm using session to store cart object in it and get it later at some point. The authnetCart is basically class for cart object.
// Check cart in session
if(isset($_SESSION['AUTHNET_CART'])) {
// Get cart from session
$authnetCart = $_SESSION['AUTHNET_CART'];
foreach($authnetCart->getCartItems() as $item) { // Line#1266
if ($item->getItemId() == $subscription_details->ID ) {
$addNewItem = false;
break;
}
}
......
You can see at line 1266, the code doesn't allow me to access its method. Any help will be highly appreciated. Thanks
You need to include / require the php with your class BEFORE session_start() like
include PATH_TO_CLASS . 'AuthnetClassFilename.php';
session_start();
if (isset($_SESSION['AUTHNET_CART'])) {
//...
}
It seems like your answer is in the error message.
Before unserializing AUTHNET_CART, include the class which defines it. Either manually, or using an autoloader.
include PATH_TO_CLASS . 'AuthnetClassFilename.php';
if(isset($_SESSION['AUTHNET_CART'])) {//...
It doesn't appear that you're actually unserializing it either (I'm assuming this was serialized before stuffing it into the session?)
if(isset($_SESSION['AUTHNET_CART'])) {
// Get cart from session
/** UNSERIALIZE **/
$authnetCart = unserialize($_SESSION['AUTHNET_CART']);
foreach($authnetCart->getCartItems() as $item) { // Line#1266
if ($item->getItemId() == $subscription_details->ID ) {
$addNewItem = false;
break;
}
}
...
None of the other answers in here actually solved this problem for me.
In this particular case I was using CodeIgniter and adding any of the following lines before the line that caused the error:
$this->load->model('Authnet_Class');
OR
get_instance()->load->model('Authnet_Class')
OR
include APPPATH . '/model/Authnet_Class.php';
Did not solve the problem.
I managed to solve it by invoking the class definition in the construct of the class where I was accessing Authnet_Class. I.e.:
class MY_Current_Context_Class extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Authnet_Class');
}
// somewhere below in another function I access Authnet_Class ...
I now understand that the context where you access the Authnet_Class class, needs to have its definition present on the context's class construct (and not just before you invoke the properties of Authnet_Class).
I do not recommend this technique, but there is a way to get around this error :
if( get_class($myObject)=='__PHP_Incomplete_Class' )
$myObject = unserialize(preg_replace('/^O:\d+:"[^"]++"/', 'O:'.strlen('MyClass').':"MyClass"', serialize($myObject)));
Having a good site architecture is obviously the right solution, but it can help temporarily until the problem is fixed
If you're using an MVC framework with a front controller, you need to have your autoload statement before your session_start statement:
[front controller]
//Do this before session start because session has an object that will not work
// if the class has not been loaded already
require_once('vendor/autoload.php');
//Start a session AFTER autoloading
session_start();