Set A variable from other Variable in a class without function - php

I started using classes in PHP, and I have the following code:
class webConfig
{
public $SALT1 = "3525";
public $SALT2 = "2341";
public $SALT3 = $SALT1.$SALT2;
}
But this gives me 500 Internal Server Error, which means that I am doing something wrong.
Is there any way of doing this without using any function, including construct?
This does not work aswell:
class webConfig
{
public $SALT1 = "3525";
public $SALT2 = "2341";
public $SALT3 = $this->SALT1.$this->SALT2;
}

In PHP; Expressions are not allowed as Default Values of any Property. For this reason, PHP is simply saying that you should not even imagine doing that in the first place. But, fortunately then; this is why you have the Constructor Method — to help you initialize some class Properties, assign Default values to Member Properties using Expression (like in your case), etc.... Using a Constructor, your class could look like the Snippet below and it is expected to work as well:
<?php
class webConfig {
public $SALT1 = "3525";
public $SALT2 = "2341";
public $SALT3;
public function __construct(){
// SET THE VALUE $SALT3 HERE INSTEAD
$this->SALT3 = $this->SALT1 . $this->SALT2;
}
}
Alternatively; you may even initialize all the Properties of the Class within the Constructor like so:
<?php
class webConfig {
public $SALT1; //<== NOTICE THAT THIS PROPERTY IS NOT INITIALIZED.
public $SALT2; //<== NOTICE THAT THIS PROPERTY IS NOT INITIALIZED.
public $SALT3; //<== NOTICE THAT THIS PROPERTY IS NOT INITIALIZED.
public function __construct(){
$this->SALT1 = "3525";
$this->SALT2 = "2341";
$this->SALT3 = $this->SALT1 . $this->SALT2; //<== YET AGAIN; SET THE VALUE
//<== OF $SALT3 LIKE BEFORE
}
}

Related

PHP use variable of class in other class

I basically know php but i am new to all that classes-stuff. For now - love it.
Here is my problem:
I'm writing a class to do all that stuff around the account-managements. (e.g. create new account, get account details, check if account exists .... )
Within that class i need to do some MySQL-requests. Therefor i i'm using the medoo-class (http://www.medoo.in).
class acc{
// Attributes
public static $account;
public $pw;
protected $error;
public function acc_exist() {
$database = new medoo();
$acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);
if ($acc_count == 0) {return true;} else {$this->error .= "Account exists already!";};
}};
Please note the line:
$database = new medoo();
and
$acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);
here i bring in medoo. And ["column_account" => acc::$account] acctually works. As i read in some other posts, i made $accounts public static.
now i call my class like this:
$my_acc = new acc();
$my_acc->account = 'Luci';
$my_acc->acc_exist();
i need to work like that. Doing some acc($account) is difficult in context of the rest of my code.
But as i expected, i get an error:
Strict Standards: Accessing static property acc::$account as non static
clear to my that static holds the var's value. so i will need some other way. Anyone got an idea?
best, Lox
I don't think you need to have $account as static, that wouldn't make sense with the way you're probably going to be using this code, try having public $account; and then use ["column_account" => $this->account]
So:
class acc{
// Attributes
public $account;
public $pw;
protected $error;
public function acc_exist() {
$database = new medoo();
$acc_count = $database->count("table_accounts", ["column_account" => $this->account]);
if ($acc_count == 0) {return true;} else {$this->error .= "Account exists already!";};
}};
Here's more information on how to use static properly: Static Keyword in PHP
You are calling a variable that doesn't exist.
You declared $accout as public and static.
But you attempt calling $account.
Replace:
$my_acc->account = 'Luci';
With:
$my_acc->accout = 'Luci';
Vex is right. Take off the static keyword and use ["column_account" => $this->account] instead.
Bests,
B.

PHP Class: Array deinitialized after constructor?

Im making a class in php, but Im having some problems with one of the class variables. I declare a private variable, then in the constructor set it. However, later in the class I have a method that uses that variable. The variable in this case is an array. However, the method says the array is blank, but when I check it in the constructor, it all works out fine. So really the question is, why does my array clear, or seem to clear, after the constructor?
<?php
class Module extends RestModule {
private $game;
private $gamearray;
public function __construct() {
require_once (LIB_DIR."arrays/gamearray.php");
$this->gamearray = $gamesarray;
$this->game = new Game();
$this->logger = Logger::getLogger(__CLASS__);
$this->registerMethod('add', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), true);
$this->registerMethod('formSelect', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), false);
}
public function add(){
$game = Utility::post('game');
}
public function formSelect(){
$gamename = Utility::get('game');
$this->$gamearray[$gamename];
}
}
The array is pulled in from another file because the array contains a lot of text. Didn't want to mash up this file with a huge array declared in the constructor. The scrolling would be tremendous. Any explanation would be nice, I like to understand my problems, not just fix em'.
You have a typo:
public function formSelect(){
$gamename = Utility::get('game');
$this->gamearray[$gamename]; // Remove the $ before gamearray
}
Moreover, in your case, include is better than require_once.
If you want to go deeper, you could rewrite $gamearray assignment like this:
// Module.php
$this->gamearray = include LIB_DIR.'arrays/gamearray.php';
// gamearray.php
return array(
// Your data here
);

PHP OOP: Accessing Variables

I have the following "Student" Class:
class Student {
public $user_id;
public $name;
public function __construct($user_id) {
$info = $this->studentInfo($user_id);
$this->name = $info['name'];
$this->is_instructor = $info['is_instructor'];
$this->user_id = $info['id'];
}
public static function studentInfo($id) {
global $db;
$u = mysql_fetch_array(mysql_query("SELECT * FROM $db[students] WHERE id='$id'"));
if($u) {
return $u;
}
}
public static function getCoursesByInstructor() {
global $db;
return mysql_query("SELECT courses.*, course_types.name FROM $db[courses] as courses
JOIN $db[course_types] as course_types ON courses.course_type_id=course_types.id
WHERE instructor_id='$this->user_id'");
}
}
I'm trying to do:
$u = new Student(1);
$courses = $u->getCoursesByInstructor();
But am getting the following error:
Fatal error: Using $this when not in object context in /Applications/MAMP/htdocs/flight1/phpincludes/classes/students.class.php on line 54
You're getting that error because you're function is a static function, and therefore you cannot use the $this pointer within it because it supposed to point to an object. So just remove the static keyword from your function definitions.
You are using static methods non-statically. Static methods are only bound to its class, but not to an object, thus $this is not available. This especially means, that $this->userid, that you use in getCoursesByInstructor(), is not valid. I recommend to make the method non-static.
public function getCoursesByInstructor() { /* your code here */ }
Remove the static keyword from the functions you declared inside your Student class.
The static keyword is, simply put, used to indicate a function that is accessible without the need of creating an instance of that class. On the other hand, $this is used to refer to class instance variables. That's why those two don't go well togheter, you're trying to access an instance variable (by using $this) in a static context.
The issue with your code is you are requesting $this inside your static function. See this. You have $this->user_id inside the query.
return mysql_query("SELECT courses.*, course_types.name FROM $db[courses] as courses
JOIN $db[course_types] as course_types ON courses.course_type_id=course_types.id
WHERE instructor_id='$this->user_id'");
To fix this issue you have to modify this function. I can suggest you following way.
public static function getCoursesByInstructor($userID) {
global $db;
return mysql_query("SELECT courses.*, course_types.name FROM $db[courses] as courses
JOIN $db[course_types] as course_types ON courses.course_type_id=course_types.id
WHERE instructor_id='$userID'");
}
And you have to change your other functions with the same theory.
Cheers !

Accessing a global array inside class constructor

My aim is to retrieve some data from a global array which is defined in another PHP file. My code is running inside database.php file and the array I want to use is inside config.php file. I understand that accessing a global array inside class is not a good idea, but I want to do it so because of some reasons.
My code is as below:
config.php
$CONFIG = array();
// ...
$CONFIG["DATABASE"] = array();
$CONFIG["DATABASE"]["USERNAME"] = "user";
$CONFIG["DATABASE"]["PASSWORD"] = "pass";
$CONFIG["DATABASE"]["HOSTNAME"] = "127.0.0.1";
$CONFIG["DATABASE"]["DATABASE"] = "my_db";
// ...
database.php
require('config.php');
class Database
{
protected $m_Link;
private $m_User;
private $m_Pass;
private $m_Host;
private $m_Data;
private $m_bConnected;
public function __construct()
{
global $CONFIG;
$this->m_User = $CONFIG["DATABASE"]["USERNAME"];
$this->m_Pass = $CONFIG["DATABASE"]["PASSWORD"];
$this->m_Host = $CONFIG["DATABASE"]["HOSTNAME"];
$this->m_Data = $CONFIG["DATABASE"]["DATABASE"];
$this->m_bConnected = false;
$this->Connect();
}
// ...
};
There is no error given (except for the failed database connection notification).
I can't access to the array elements. For instance $CONFIG["DATABASE"]["USERNAME"] returns an empty value even though it was initialized with "user" string in the config.php.
How should I modify my code so that it can this global array can be accessible inside the class constructor?
(Note: PHP version is 5.3.0)
Your code looks right, so I think you should just debug it. Try to output $CONFIG before creating instance of Database class, $CONFIG may be redefined/changed somewhere in your code. And don't just check one value in array - output whole array with var_dump/print_r.
Instead of
$CONFIG = array();
use
$GLOBALS['CONFIG'] = array();
I think some how global is not working in __construct(). I am not sure if it is a bug or it is designed as it is.
For code
<?php
class Test {
public $value;
function __construct() {
global $value;
$value = "I am a test.";
}
}
$test = new Test();
echo $test->value;
You will see nothing when above php runs.
However, if you do not use global, but use $this->value, everything works fine.
<?php
class Test {
public $value;
function __construct() {
$this->value = "I am a test.";
}
}
$test = new Test();
echo $test->value;
If you insist to get a reason. I think maybe __construct() is design to initialize the properties. Some code like $this->value = $value is using a lot in __construct(). So maybe the php designer thinks it is not good practice to use global in __construct(). However. I can not find a word mentioned it in php manual after all.

call another class's function inside a class

i have 2 classes
for DB
for language
i want to use my language things in the DB
so it outputs the result
ex :
class db_control{
var $db_connection, $lang_var;
//create the function for the connection
function db_connect(){
//define some variables
global $db_host, $db_username, $db_password, $db_name, $lang_var;
$this->db_connection = mysql_connect("$db_host","$db_username","$db_password")or die("can't connect to server with these informations");
//checl that the connection is established
if($this->db_connection){
echo $lang_vars->getvar("$langvals[lang_con_est]");
}
but this
$lang_vars->getvar("$langvals[lang_con_est]");
doesn't work
i mean it outputs many problems
and am sure my problem is that i didn't define my variables and classes correctly
P.S : the language class is in file called language.php and this part is in DB.MySQL.php
EDIT :
this is the language class
class lang_vars{
public static function getvar($variable){
return $variable;
}
}
i want the DB class to display text from the language class
thats why i used
echo $lang_vars->getvar("$langvals[lang_con_est]");
but it doesn't work
cuz when i declare the language class
$lang_vars = new lang_vars;
inside the db_control it shows error unexpected T_something expected T_Function
and when i declare it outside nothing up
hope i made things more clear now
Any reason why you are still using PHP4 syntax?
When creating an instance of the db_control class, pass the object to be stored as $lan_var into the constructor or set it via a dedicated setter. See Dependency Injection.
class DBControl
{
protected $_lang;
public function __construct($lang = NULL)
{
if($lang !== NULL) {
$this->_lang = $_lang;
}
}
public function setLang($lang)
{
$this->_lang = $lang;
}
}
Then do either
$dbControl = new DBControl(new LangThing);
or
$dbControl = new DBControl;
$dbControl->setLang(new LangThing);
Also, get rid of the globals. Pass those in via Dependency Injection too.
Make your language class methods static . Read more here.
class LangClass
{
public static function getvar()
{
// your code here
}
}
Then, you can use its functions without creating objects like this:
$LangClass::getvar("$langvals[lang_con_est]");
This can do the trick.
$lang_vars = new LanguageClassOrWhateverItIsCalled();
$lang_vars->getvar($langvals[lang_con_est]);
But maybe you should think of making it a static method. In that case you can call it with:
LanguageClassOrWhateverItIsCalled::getVar($langvals[lang_con_est]);
You can define the method static like:
public static function getVar() {
// Do something
}
Edit: #SAFAD
You should use the static method for this. To make this work, be sure your class language.php is loaded. To do so just add in the DB.MYSQL.php file the following line:
require_once('language.php');
class db_control {
...
Make sure you have the right path to the language.php file.
Then you should call the method in db_control class like this:
if($this->db_connection){
echo lang_vars::getvar("$langvals[lang_con_est]");
}
Besides, what is the use of a function like this? You should either do:
if($this->db_connection){
echo $langvals[lang_con_est];
}
or change your static getvar method to:
public static function getvar($variable){
return $langvals[$variable];
}
and your function call to:
if($this->db_connection){
echo lang_vars::getvar("lang_con_est");
}

Categories