Didn't know how to ask this question.
I was working on setting up class to handle my Database interaction and have a weird interaction of passing variables. I must be missing something.
I have a class DataBaseAPI I have a function QueryDB($value) that will be called by other functions. But it has an issue with my declaring that $value inside another function. Example:
Works
include_once('DataBaseAPI.php');
$DB = new DataBaseAPI();
$test = $DB->QueryDB('id');
echo $test;
Doesn't Work
include_once('DataBaseAPI.php');
$DB = new DataBaseAPI();
$test = $DB->getId();
echo $test;
Start of the class in DataBaseAPI.php
class DataBaseAPI {
public function getId(){
//the same function defined the same way but needing to use $this
$this->QueryDB('id');//seems like a waste here but is for ease of use later on
}
public function QueryDB($value){
echo $value; //echo's id
global $conn;
$token = '7ci4f8ykfik3ndzufksy1dp16x3na4'; //Test Token not a real token
$doesExists = "SELECT $value FROM user_info WHERE token='$token'";
$existsResult = mysqli_query($conn, $doesExists);
$check = $existsResult->fetch_assoc();
return $check[$value];
}
}
I even checked with an echo the $value in the QueryDB($value) echo's id the same way as when I call the function directly.
I just don't understand why the first method works yet the second method doesn't, yet I'm still calling it the same way. Just inside another function.
Return the result of getId() in order to store in your $test. Do
public function getId(){
return $this->QueryDB('id');//seems like a waste here but is for ease of use later on
}
instead of
public function getId(){
$this->QueryDB('id');//seems like a waste here but is for ease of use later on
}
Related
Good day. I'm trying to execute a function. i declare a global variable to get data (variable) outside the function, and the function i put inside a public function of a Class.
class Test {
public function execute(){
$data = "Apple";
function sayHello() {
global $data;
echo "DATA => ". $data;
}
sayHello();
}
}
$test = new Test;
$test->execute();
The expected result:
DATA => Apple
The real result:
DATA =>
the global variable is not getting the variable outside the function. Why it happened? Thank you for the help.
$data is not a global variable. It's inside another function, inside a class. A global variable sits outside any function or class.
But anyway your use case is unusual - there's rarely a need to nest functions like you've done. A more conventional, logical and usable implementation of these functions would potentially look like this:
class Test {
public function execute(){
$data = "Apple";
$this->sayHello($data);
}
private function sayHello($data) {
echo "DATA => ". $data;
}
}
$test = new Test;
$test->execute();
Working demo: http://sandbox.onlinephpfunctions.com/code/e91b98bb15fcfa71b1c6cbbc305b5a93df678e8b
(This is just one option, but it's a reasonable one, although since this is clearly a reduced, abstract example, it's hard to be sure what your real scenario would actually require or be best served by.)
I need to access the global variable from another function. First I have assigned the value to global variable in one function. When I am trying to get that value from another function, it always returns null. Here my code is
StockList.php
<?php
$_current;
class StockList
{
public function report(){
global $_current;
$_current = 10;
}
public function getValue(){
print_r($GLOBALS['_current']);
}
}
?>
Suggestion.php
<?php
include ("StockList.php");
$stk = new StockList();
$stk->getValue();
?>
Thanks in advance.
Man, its hard to understand what are you trying to do as you said you have called report() in your index.php
Anyways, when dealing with classes, to set variable values, standard procedure is as following:
class StockList
{
public $_current;
public function setValue($value){
$this->current = $value;
}
public function getValue(){
return $this->current;
}
}
And after whenever you wanna use the class:
<?php
include ("StockList.php");
$stk = new StockList();
$stk->setValue(10);
$_current = $stk->getValue();
var_dump($_current);
?>
This is basic idea of OOP, benefits of this approach are:
You can dynamically set value of $_current.
Your getValue() function is not dedicated for printing the value of the variable, thats why you can use that function only for getting the value and then do whatever you want with it.
I'm new to PHP so still getting grips of how constructs work and I'd appreciate some help!
The following code is failing to echo the variables $arrivalTime and $hourStay:
class Variable {
public $arrivalTime;
public $hourStay;
public function __construct() {
$this->arrivalTime = $_POST['arrivalTime'];
$this->hourStay = $_POST['hourStay'];
echo $this->arrivalTime;
echo $this->hourStay;
}
}
You need to instantiate the class, by calling new Variable() somewhere in your code. However, in general it is better to not have your class depend on the post variables, but pass them in through the constructor:
class Variable {
public $arrivalTime;
public $hourStay;
public function __construct($arrivalTime, $hourStay) {
// TODO: Check if the values are valid, e.g.
// $arrivalTime is a time in the future
// and $hourStay is an integer value > 0.
$this->arrivalTime = $arrivalTime;
$this->hourStay = $hourStay;
}
public function print() {
echo $this->arrivalTime;
echo $this->hourStay;
}
}
$var = new Variable($_POST['arrivalTime'], $_POST['hourStay']);
$var->print();
Also note how I took the generation of output away from the constructor. Its only task should be to initialize the object to a valid state. Processing input or generating output is not its responsibility.
I try to create some sort of setup class, like global values for the page.
The PHP-code
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
Question
My class forget the value I set. Why is that?
Do I have to use global variables?
Is this the correct approach for the problem?
The variable is set on an object, not on a class.
For each class, you can instantiate multiple objects. Each of those have their own variable scope.
Edit:
I forgot to include the easiest, and least verbose solution to your problem. AFAIK, you're looking for a way to check what page you're on. Constants will do just that:
defined('MY_CURRENT_PAGE') || define('MY_CURRENT_PAGE','My Value');
//use anywhere like so:
echo 'Currently on page: '.MY_CURRENT_PAGE;
My class forget the value I set. Why is that?
Quite simple: your page member function isn't static, yet you call it as though it is: get::page(). Even if you were to fix this, you're creating a new instance in the page method, but you're not preserving a reference too it anywhere, so each page call will create a new globals instance, that has nothing set.
Do I have to use global variables?
No, unless you're Really desperate, never use globals
Is this the correct approach for the problem?
No, if it doesn't work, it's not correct (IMHO).
Well, what is, you might ask. There are several ways to go about this:
class globals
{
public static $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
private $_globalsInstance = null;
public function __construct(globals $instance = null)
{
$this->_globalsInstance = $instance;
}
private function _getGlobals()
{
if (!$this->_globalsInstance instanceof globals)
{
$this->_globalsInstance = new globals();
}
return $this->_globalsInstance;
}
public function page()
{
return $this->_getGlobals()::$page;
}
}
Personally, however, I wouldn't work like this, I'd just pass my instances to wherever I need them (as arguments to functions/methods or just instantiate them in a scope that will be accessible:
class globals
{
public $page = null;//make this static, meaning all instances will share this var
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
}
$page = new globals();
$page->set_page('foobar');
someFunction($page);
$someObject->renderPage($page);
require_once('specificScript.php');
//inside required script:
echo $page->page;
Do I have to use global variables?
Not, if your can use PHP 5.3
Is this the correct approach for the problem?
Better to use a generic class for this, or use static properties of objects
<?php
class globals
{
public static $page;
public function __construct()
{
}
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get
{
public static function page()
{
return globals::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page(); // Short function to be in a template
P.S.
But this is not a nice approach
$globals there
class get
{
public function page()
{
$globals = new globals();
return $globals->page;
}
}
and there
$globals = new globals();
$globals->set_page('My value');
are different inctances of globals class.
One of the solutions is to make $page var static
public static $page;
I hope this helps
UPD:
Also you might apply Singleton to globals class and request for its insnance instead of creating new one directly:
globals::getInstance()->setPage('Page');
and
return globals::getInstance()->getPage();
In this case $page doesn't have to be static.
I'm not sure the other answers are very clear. You have created 2 classes. As such they have different scopes. As writen you can't access the original variable $page from the get class because it's outside the scope. Your page function in fact creates a new version of the object $globals without $page set. Normally you would place both your set and get functions in the initial object/class. Though it would be possible to use two class by calling the first class from the second and setting the page. Why you would want to do that I'm not sure.
if I were writing the class it would look like this.
class globals
{
public $page;
public function __construct()
{
}
public function set_page($value)
{
$this->page = $value; // Maybe from a database
}
public function get_page()
{
return $this->page;
}
}
Actually I would probably set page to private not public. As public I guess you don't need a get function.
for using methods of the class without object you must use static definition. but anyway you put value for one class object and try to get it from another...
Perhaps this will help you continue on your coarse:
class globals
{
public static $page;
public function set_page($value)
{
self::$page = $value; // Maybe from a database
}
}
class get extends globals
{
public function page()
{
$globals = new globals();
return parent::$page;
}
}
$globals = new globals();
$globals->set_page('My value');
echo get::page();
?>
I know you can assign a function's return value to a variable and use it, like this:
function standardModel()
{
return "Higgs Boson";
}
$nextBigThing = standardModel();
echo $nextBigThing;
So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing something?
class standardModel
{
private function nextBigThing()
{
return "Higgs Boson";
}
public $nextBigThing = $this->nextBigThing();
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing; // get var, not the function directly
I know I could do this:
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel;
echo $standardModel->nextBigThing(); // Call to the function itself
But in my project's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.
I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.
But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?
Obviously, the examples are made up to simplify things. Please don't question "why" I need to put said function in the class. I don't need a lesson on proper OOP and this is just a proof of concept. Thanks!
public $nextBigThing = $this->nextBigThing();
You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.
Do this:
class standardModel {
public $nextBigThing = null;
public function __construct() {
$this->nextBigThing = $this->nextBigThing();
}
private function nextBigThing() {
return "Higgs Boson";
}
}
You can't assign default values to properties like that unless that value is of a constant data type (such as string, int...etc). Anything that essentially processes code (such as a function, even $_SESSION values) can't be assigned as a default value to a property. What you can do though is assign the property whatever value you want inside of a constructor.
class test {
private $test_priv_prop;
public function __construct(){
$this->test_priv_prop = $this->test_method();
}
public function test_method(){
return "some value";
}
}
class standardModel
{
// Public instead of private
public function nextBigThing()
{
return "Higgs Boson";
}
}
$standardModel = new standardModel(); // corection
echo $standardModel->nextBigThing();