Php class variables undefined variable

Undefined private variables

I am just curious why I am getting such notices, although the variable has been defined in the private section of the class. Can’t I use private data member of the class in the member function (because that would defeat the whole concept of OOP)? The php file is:

class data_base //helps handling permissins < private $host; private $user; private $password; public function feed_data($hst, $usr, $pwd) < $host=$hst; $user=$usr; $password=$pwd; >public function get_data() < $info=array("host"=>" ", "user"=>" ", "password"=>" "); $info['host']=$host; $info['user']=$user; $info['password']=$password; return $info; > > $user1=new data_base; $user2=new data_base; $user1->feed_data("localhost", "root", ""); //enter details for user 1 here $user2->feed_data("", "", ""); //enter details for user 2 here $perm_add=$user1->get_data(); $perm_view=$user2->get_data(); 

2 Answers 2

In PHP you must call a property as a property

$this->host; // instead of $host; 

Unlike for example in java $host is always a local variable and thus undefined here.

As a sidenote: You can write

$info=array("host"=>" ", "user"=>" ", "password"=>" "); $info['host']=$host; $info['user']=$user; $info['password']=$password; return $info; 
return array( 'host' => $this->host, 'user' => $this->user, 'password' => $this->password ); 

It’s short and imo more reable (No need for a temporary variable)

Источник

Исправление ошибки «Notice: undefined variable» в PHP

Ошибка undefined variable появляется при попытке обратиться к не существующей (не объявленной ранее) переменной:

Если в настройках PHP включено отображение ошибок уровня E_NOTICE, то при запуске этого кода в браузер выведется ошибка:

Notice: Undefined variable: text in D:\Programs\OpenServer\domains\test.local\index.php on line 2

Как исправить ошибку

Нужно объявить переменную перед обращением к ней:

Нет уверенности, что переменная будет существовать? Можно указать значение по-умолчанию:

Читайте также:  Королевский питон особенности содержания

Есть ещё один вариант исправления этой ошибки — отключить отображение ошибок уровня E_NOTICE:

Не рекомендую этот вариант. Скрытие ошибок вместо их исправления — не совсем правильный подход.

Кроме этого, начиная с PHP 8 ошибка undefined variable перестанет относиться к E_NOTICEи так легко отключить её уже не удастся.

Если ошибка появилась при смене хостинга

Часто ошибка возникает при переезде с одного сервера на другой. Практически всегда причина связана с разными настройками отображения ошибок на серверах.

По-умолчанию PHP не отображает ошибки уровня E_Notice, но многие хостинг-провайдеры предпочитают настраивать более строгий контроль ошибок. Т.е. на старом сервере ошибки уже были, но игнорировались сервером, а новый сервер таких вольностей не допускает.

Остались вопросы? Добро пожаловать в комментарии. 🙂

Источник

How do I fix «Undefined variable» error in PHP?

Today, I have started to learn PHP. And, I have created my first PHP file to test different variables. You can see my file as follows.

Test variables inside the function:

"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; > myTest(); echo "

Test variables outside the function:

"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; ?>

Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19 Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29

8 Answers 8

The first error ( $x is undefined) is because globals are not imported into functions by default (as opposed to «super globals», which are).

You need to tell your function you’re referencing the global variable $x :

function myTest() < global $x; // $x refers to the global variable $y=10; // local scope echo "

Test variables inside the function:

"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; >

Otherwise, PHP cannot tell whether you are shadowing the global variable with a local variable of the same name.

The second error ( $y is undefined), is because local scope is just that, local. The whole point of it is that $y doesn’t «leak» out of the function. Of course you cannot access $y later in your code, outside the function in which it is defined. If you could, it would be no different than a global.

Источник

php undefined variable / not detecting class

i’m working for some fun projects but i’m stuck at the moment. every time i call my index.php i get a notice and a fatal error. Notice: Undefined variable: translator in C:\xampp\htdocs\Curve\manage\pages\menu.sfwp on line 309 Fatal error: Call to a member function getText() on a non-object in C:\xampp\htdocs\Curve\manage\pages\menu.sfwp on line 309 i required all files and called my class. structure: index.php -> core/core.inc.php -> classes/Translator.cs.php index.php -> pages/menu.sfwp core:

if(corekey != "STR456512013213280935405CMS") < die(); >//Sessionn session_start(); //MySQL Connection try< $conn = new PDO("mysql:host=localhost;dbname=Curve", 'root', ''); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $Exception)< throw new Exception( $Exception->getMessage( ) , $Exception->getCode( ) ); > //classes require('classes/General.cs.php'); require('classes/Users.cs.php'); require('classes/Portal.cs.php'); require('classes/Translation.cs.php'); $users = new users($conn); $general = new general($conn); $portal = new portal($conn); $templatePortal = new portalTemplate($conn); $translator = new Translator($conn); 
class Translator < private $db; public function __construct($database) < $this->db = $database; > private function getTxt($text, $userlang)< $lang = "lang_".$userlang; $query = $this->db->prepare("SELECT * FROM ".$lang." WHERE "); $query->execute(); $row = $query->fetch(); echo($row->text); > > 

Источник

Undefined Variable PHP_SELF

@FirmView: Nah, we don’t do that anymore. While the associated problems mainly arise from running all other code in global scope as well, it’s best for newcomers to eschew that feature.

8 Answers 8

Do not use any of the suggested versions of PHP_SELF. It is a security nightmare, opening up your PHP to a multitude of possible injection attacks.

What are you trying to achieve? Generate the URL for a form sending to itself? Use action=»» for that — it is a valid approach and will always use the URL for sending the form as for loading.

If you must know the requested script, use $_SERVER[‘SCRIPT_NAME’] instead.

You are using $PHP_SELF it should be

define("PHP_SELF",$_SERVER['PHP_SELF']); echo PHP_SELF ; 

@DavidRamirez Your way is wrong, and your reasoning «it has worked ok» is flawed. In general PHP_SELF doesn’t contain any characters that would be changed by htmlentities() , so it is natural that it works with positive cases. But you must want to have perfect protection against ANY attack — only making it «more resilient to injection attacks» simply isn’t enough, these type of attack must be made completely impossible! And it is possible to do so, but it requires knowledge about how to correctly escape data — your solution isn’t such.

Are you trying to access $_SERVER[‘PHP_SELF’] ?

Looks like certain WordPress distributions declare $PHP_SELF = $_SERVER[‘PHP_SELF’] for reasons I can’t say, must be some sorta legacy thing.

Источник

Оцените статью