use main file's variable inside class PHP - php

i have a main php file which contains the variable:
$data['username']
which returns the username string correctly.
In this main file i included a class php file with:
require_once('class.php');
they seem linked together well.
My question is: how can I use the $data['username'] value inside the class file? I'd need to do an if statement to check its value inside that class.
class.php
<?php
class myClass {
function __construct() {
if ( $data['username'] == 'johndoe'){ //$data['username'] is null here
$this->data = 'YES';
}else{
$this->data = 'NO';
}
}
}

There are many ways to do that, we could give you accurate answer if we knew how your main php file and the class look like. One way of doing it, from the top of my head:
// main.php
// Instantiate the class and set it's property
require_once('class.php');
$class = new myClass();
$class->username = $data['username'];
// Class.php
// In the class file you need to have a method
// that checks your username (might look different in your class):
class myClass {
public $username = '';
public function __construct() {}
public function check_username() {
if($this->username == 'yourvalue') {
return 'Username is correct!';
}
else {
return 'Username is invalid.';
}
}
}
// main.php
if($class->username == 'yourvalue') {
echo 'Username is correct!';
}
// or
echo $class->check_username();

If the variable is defined before the call to require_once then you could access it with the global keyword.
main.php
<?php
$data = [];
require_once('class.php');
class.php
<?php
global $data;
...
If your class.php is defining an actual class then I would recommend Lukasz answer.
Based on your update I would add the data as a parameter in the constructor and pass it in on instantiation:
<?php
require_once('class.php');
$data = [];
new myClass($data);
Adjusting your constructor to have the signature __construct(array $data)

Related

Codeigniter: Using static variable

I am making a website in which i have to save a global variable.
I am using this person code globals_helper.php custom global variable class
But i always get static variable value null.
globals_helper.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Application specific global variables
class Globals
{
private static $authenticatedMemberId = null;
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$authenticatedMemberId = null;
self::$initialized = true;
}
public static function setAuthenticatedMemeberId($memberId)
{
self::initialize();
self::$authenticatedMemberId = $memberId;
}
public static function authenticatedMemeberId()
{
self::initialize();
return self::$authenticatedMemberId;
}
}
I have done all the steps like add globals_helper.php in helper folders and updated autoload file. Now I am trying to access those static variable from a custom library "Ctrl_utility" function "get_search_term" and my controllers calling get_search_term function
Ctrl_utility.php
class Ctrl_utility {
protected $CI;
public static $static_search = "";
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function get_search_term($searchTerm){
$searchTerm = $this->CI->security->xss_clean(htmlspecialchars($searchTerm));
if (isset($searchTerm) && strlen($searchTerm)>0) {
Globals::setAuthenticatedMemeberId($searchTerm);
} else {
$searchTerm = Globals::authenticatedMemeberId();
}
return $searchTerm;
}
One of my controller and they all have class ctrl_utility, get_search_term function:
class Blog_controller extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->model('blogs_model');
}
public function index(){
//Get SearchTerm Values
$searchTerm = $this->ctrl_utility->get_search_term($this->input->post('searchTerm'));
//Get Url First Parameter
$start = $this->ctrl_utility->get_url_first_parameter();
// Get Data from solr
$rows = 10;
$data = $this->blogs_model->solrData($start, $rows, $searchTerm); //give start of documents
//Pagination
$this->pagination->initialize($this->ctrl_utility->pagination_config($this->uri->segment(1), $rows, $data['found']));
//Views
$this->load->view('tabs/blogs', $data);
}
}
Am i doing something wrong?
Now when it comes to define them in CodeIgniter, there are several ways do that. I’ve listed some of them below:
Create your own file in application/libraries in which class constructor contains an array as an argument. Now create a new file in /application/config with same name as given in application/libraries and declare your global variables in it. Now to use these variables, autoload the newly created library.
Create your own file in application/core and declare the global variables in it. Than in controller you need to extend your file name instead of CI_Controller.
If the Global Variables are true constants, just add them in application/config/constants.php file and name them in all uppercase like the others are defined.
If you want to set application constants create new config file and add the variables. Now load it as $this->config->load(‘filename’); And access those variables as
$this->config->item(‘variable_name’);
Instead of creating helper create a library
Step 1: First of all, open application/libraries and create a custom
class name globals.php. It contains a constructor function which
contains an array as an argument.
<?php
class Globals {
// Pass array as an argument to constructor function
public function __construct($config = array()) {
// Create associative array from the passed array
foreach ($config as $key => $value) {
$data[$key] = $value;
}
// Make instance of CodeIgniter to use its resources
$CI = & get_instance();
// Load data into CodeIgniter
$CI->load->vars($data);
}
}
?>
Step 2: Now to make config file, open application/config and create
file as globals.php and write the code given below. This file contains
the config variable which will be passed as an array to constructor of
Globals class where its keys and values are stored in $data
<?php
// Create customized config variables
$config['web_Address']= 'https://www.example.com/blog';
$config['title']= 'CodeIgniter Global Variable';
?>
When constructor function loads, it will take the config variables
from the config file in order to use these variables anywhere.
Note: Name of the above file must be same as the class created in
libraries folder otherwise the code will not work.
Step 3: But before using these variables we have to autoload the newly
created library globals as given below.
And load library in autoload
$autoload['libraries'] = array('globals');
Now, you can use global variables in your controller
<?php
class CI_Global_Variable_Tutorial extends CI_Controller{
public function __construct() {
parent::__construct();
}
// Load view page
public function index() {
$this->load->view('show_global_variables');
}
}
?>
Views : show_global_variables.php
In view page, we can use global variables according to our need.
<?php
echo "Title of the blog post : ".$title;
echo "<a href='$web_Address'>"."Click here to go to blog page"."</a>";
?>

using same namespace php, Call to undefined function

using same namespace php
I have this files in the same folder :
OtherFunctions.php
<?php
namespace Pack\sp;
$Tble = NULL;
function SetTble($tble) {
global $Tble;
$Tble = $tble;
}
function GetTble() {
global $Tble;
return $Tble;
}
function Funct0($Str0, $Str1) {
return $Str0 == $Str1;
}
function Funct1($Arg) {
return "The Value is ".$Arg;
}
//... from 0 to 16
function Funct16($Arg) {
return "The Value is ".$Arg;
}
?>
How to call all functions contained in this file?
In one class File SubClass.php I have this:
<?php
namespace Pack\sp;
class SubClass {
public $CArg = "";
}
?>
In other class File LeadClass.php
I have this:
<?php
namespace Pack\sp;
use \Pack\sp\SubClass;
require_once("OtherFunctions.php");
class LeadClass {
public function __construct($Name) {
echo("_._");
$NewSC = new SubClass();
$NewSC->CArg = $Name;
SetTble($Name);
echo("ini:".GetTble().":end");
}
}
?>
I want call all function in one instruction of OtherFunctions.php File, but I don't kno how to do it....
I trying to replicate this message in other code
Fatal error: Call to undefined function GetTble() in C:...\LeadClass.php on line 10
But, I'm obtaining blank page
EDIT
Was added the line:
require_once("OtherFunctions.php");
And was replaced the line:
require_once("SubClass.php");
by the line:
use \Pack\sp\SubClass;
in LeadClass.php File.
But, I'm obtaining blank page
You need to add the next line
namespace Pack\sp;
use \Pack\sp\SubClass; // <--- add this
Also I think you should put the functios of the OtherFunctions file into a new class link
namespace Pack\sp;
class OtherFunctions{
// your current code goes here
}
After that you need to extend the SubClass whit the OtherFunctios class
namespace Pack\sp;
use Pack\sp\OtherFunctions;
class SubClass extends OtherFunctions {
public $CArg = "";
}
EDIT
I just tried your code and I can make the LeasClass to work as follow
<?php
namespace Pack\sp;
require_once("OtherFunctions.php");
require_once("SubClass.php");
class LeadClass {
public function __construct($Name) {
echo("_._");
$NewSC = new SubClass();
$NewSC->CArg = $Name;
SetTble($Name);
echo("ini:".GetTble().":end");
}
}
$LeadClass = new LeadClass('table');
?>
Have you already initialize the class?

How to share a dynamic variable between files in PHP(5)?

I have an object of some class that obeys the singleton pattern. I need to initialize it in one file and then use it in others. I don't know how to do this, here is what I tried :
//myClass.php
class myClass
{
private static $instance = null;
private function __construct($args)
{
//stuff
}
public function Create($args)
{
self::$instance = new myClass($args);
return self::$instance;
}
public function Get()
{
return self::$instance;
}
}
//index.php
<?php
require_once('myClass.php');
$instance = myClass::Create($args);
?>
Test Me!
//test.php
echo(is_null(myClass::Get())); //displays 1
So the problem is that from test.php, myClass::get() always returns null!
I have also tried to store the instance in the $_SESSION, which gives me the same result. Can you please point me in the right direction?
You should include file with the class difinition in each file where it used (and it should be included before it will in use).
<?php // filename: test.php
include_once("myClass.php");
$oClassInstance = myClass::Get();
var_dump($oClassInstance);
BTW
You don't need to define those two methods Create and Get. You can create only one method called getInstance:
// only one instance of the class
private static $_oInstance = null;
public static function getInstace()
{
if (!self::$_oInstance)
{
self::$_oInstance = new self();
}
return self::$_oInstance;
}
And then you can use it like:
<?php // filename: index.php
include_once("myClass.php");
// if instance does not exist yet then it will be created and returned
$oClass = myClass::getInstace();
<?php // filename: test.php
include_once("myClass.php");
// the instance already created and stored in myClass::$_oInstance variable
// so it just will be returned
$oClass = myClass::getInstance();
UPD
If you have to put some arguments into constructor just use predefined arguments:
private function __construct($aArg)
{
// this code will be launched once when instance is created
// in the any other cases you'll return already created object
}
public static function getInstance($aArgs = null)
{
if (!self::$_oInstance)
{
self::$_oInstance = new self($aArgs);
}
return self::$_oInstance;
}
ANSWER
Sorry that you have to scroll a few screens to find this =)))
The reason why you can't use myClass::Get() in you context is that you have 2 scripts that means - two different programs.
Singleton should be used within a single application (one script).
So in your case, correct usage will be module system:
- index.php
- main.php
- test.php
// file: index.php
include_once "myClass.php"
$module = $_GET["module"];
include_once $module ".php";
// file: main.php
$oClass = myClass::Create($someArgs);
var_dump($oClass); // you'll see you class body
// file: test.php
$oClass= myClass::Get();
var_dump($oClass); // you'll see the same class body as above
And your links will be:
index.php?module=main
index.php?module=test
The Create() function need to check whether $instance property already has a value before creating a new object. For example
public function Create()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
In test.php you can just call myClass::Create(), no need to have the Get() function at all

PHP Accessing parent class on an include file

A NEW UPDATE ON THE PROBLEM
I wan't the class 'BlogPost' to access its parent class variables that have been set on the main.php page
class BlogPage {
public $PageExists = false;
public $PageTitle = "no title";
public $PageId = "0";
function __construct($page){
//some sql to check if page exists
if($page_exists){
$this->PageExists = true;
$this->PageTitle = $fetched['row_title'];
$this->PageId = $fetched['row_id'];
}
}
}
class BlogPost extends BlogPage {
function __construct(){
$page_id = $this->PageId;
//some sql to get the posts that have post_page like $page_id
}
}
The Main.php page
$page = new BlogPage("index");
if($page->PageExists == true){
include("posts.php");
}else{
include("notfound.php");
}
The posts.php
$pageTitle = $page->PageTitle;
$posts = new BlogPost();
?>
If you want to access parent's class protected and public variables and functions, then you will use the parent:: static prefix.
In your case, if you want to access classOne's protected and public variables and functions inside classTwo, then you will just use parent:: inside classTwo.
If you just want to use the classTwo instantiated object on the included file, then you don't need to declare it as global, you just access it normally as you would access it a few lines below declaring it on the main file.
Update 1
You don't need to define the scope of that variable as global, because it already has that scope on that part of the script. So, just access it like this:
// global $page; remove this, no need for it
$pageTitle = $page->PageTitle;
$posts = new BlogPost();
Update 2
This is my suggested solution to your second problem:
<?php
class Page{
public $PageExists = false;
public $PageTitle = 'no title';
public $PageId = '0';
// add other options here
// add other parameters to this function
// or pass an array to it
protected function fill($page_id, $page_title){
$this->PageExists = true;
$this->PageId = $page_id;
$this->PageTitle = $page_title;
}
}
class BlogPage extends Page{
function __construct($page){
//some sql to check if page exists
if($page_exists){
parent::fill($fetched['row_id'], $fetched['row_title']);
}
}
}
class BlogPost extends Page {
function __construct($page_id){
//some sql to get the posts that have post_page like $page_id
if($post_exists){
parent::fill($fetched['row_id'], $fetched['row_title']);
}
}
}
?>
Then you can use your classes like the following...
On Main.php page
<?php
$page = new BlogPage("index");
if($page->PageExists == true){
include("posts.php");
} else{
include("notfound.php");
}
?>
On posts.php
<?php
$pageTitle = $page->PageTitle;
$posts = new BlogPost($page->PageId);
?>
if classTwo extends from classOne you will be able to do:
$two = new classTwo();
$two->functionFromClassOne();
and have access to the class.
It might be good for you to explain the exact use-case so a best approach can be recommended. Perhaps inheritance isn't the best way of achieving whatever you're trying to build.
I feel that you have your variables in classOne protected

Passing a string when calling the constructor of a class in PHP

I'm starting learning classes in PHP. I coded that:
class User {
function getFbId($authtoken) {
}
function getFbFirstName ($authtoken) {
}
}
What I want to do is something like that: $user=new User($authtoken); And pass the $authtoken to the class. It's possible to define that when starting the class. It's possible to retrieve that value inside a function of that class?
To use the variable passed in constructor throughout your class, you can create a class level variable like this:
class User {
private $tokenID = NULL;
function __construct($tokenID){
// store token id in class level variable
$this->tokenID = $tokenID;
}
function someFun($authtoken) {
echo $this->tokenID;
}
}
You need to create the constructor in order to do that:
class User {
function __construct($tokenID){
// do something with $tokenID
}
function getFbId($authtoken) {
// code
}
function getFbFirstName ($authtoken) {
// code
}
}
Note:
If you are using PHP4, a constructor can be created with a function name same as that of class like:
class User {
function User($tokenID){
// do something with $tokenID
}
function getFbId($authtoken) {
// code
}
function getFbFirstName ($authtoken) {
// code
}
}
Now you can do something like:
$user = new User($authtoken);
You are looking for contructors. See http://www.php.net/manual/en/language.oop5.decon.php
Or http://www.codewalkers.com/c/a/Programming-Basics/ObjectOriented-PHP-Constructors-and-Destructors/ for a walk through.

Categories