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
Related
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)
I've the followings classes:
abstract class utility, which contains general functions (e.g. database connection)
class get_conf, which returns the main variables that I will need almost everywhere (e.g. language, login status)
class get_data to handle the query to the database and return the results.
This is in my index file:
$init = new get_conf();
$lang = $init->lang;
$status = $init->status;
(...)
$config = new get_data($lang,$status);
This is the construct of class get_data.
class get_data extends utility {
public function __construct($lang = NULL,$status = NULL) {
$this->lang = $lang;
$this->status = $status;
}
...
Everything work fine, but I don't know how to handle at best during an ajax call.
After instantiate the class that I need,
$config = new get_data();
What is the best way to get $lang and $status? At the moment I'm calling again the functions that define their values - get_language(), check_login().
But there is a better way? Should I use sessions? It doesn't sound good to me call every time those function, especially when I have multiple ajax calls in the same page.
EDIT: I'm sorry, is my fault cause I formulated the question in the wrong way. What I would need is to get the variables from Ajax and ok, but I would need to use them in the class
For example, in the class get_data I've this function:
public function get_category($id_cat) {
$q = "SELECT category FROM p_category WHERE id = '".$id_cat."' AND code = ".$this->lang.";
return $this->exe_query($q);
}
Cause I'm calling this function both from Ajax and not, depending on the situation, $this->lang is defined only when I call it out of an Ajax request. And even using static var doesn't work with Ajax.
Write the following member function inside get_data class:
public function getCVar($var){
$c = new get_data();
eval('$tmp = $c->'.strtolower($var).';');
return $tmp;
}
Then you can get the variables value like below:
echo get_data::getCVar('lang');
echo get_data::getCVar('status');
Try it:
class get_data extends utility {
static $lang = null;
static $status = null;
public function __construct($lang = NULL,$status = NULL) {
if($lang !== null){
self::$lang = $lang;
}
if($status !== null){
self::$status = $status;
}
}
}
$config = new get_data($lang,$status);
echo get_data::$status;
echo get_data::$lang;
I wanna get value from Class PHP without initialize this Class.
For this I give the file path where this class, for it to be reviewed, but not initialized.
My Idea:
<?php
$reflection = new ReflectionClass( '/var/www/classes/Base.php' );
$version = $reflection->getProperty('version')->getValue( );
if( $version >= 1 )
{
return true;
}
return false;
?>
BASE.PHP
<?php
class Base
{
private $version = 2;
}
?>
whats about static? its much simpler:
<?php
class Base
{
public static $version = 2; // or $version = array(1,2,3);
}
if(is_array(Base::$version)) {
print_r(Base::$version);
} else {
echo Base::$version;
}
?>
How about a protected variable with a getter.
class Base {
protected $version = array(2,3,4,5,6);
public function __version() { return $this->version; }
}
You can instantiate this anywhere you like, or extend it to add functions to it. The version will be constant across any extensions, so bear that in mind.
Usage is as simple as $yourClass->__version(). Named it similar to a magic method's name in order to prevent function name collision. It can be redefined by extensions if needed.
I don't have alot of experience with OOP programming in PHP, and my search has given no result but solutions to direct methods. What I need is this:
// URL Decides which controller method to load
$page = $_GET['page'];
// I want to load the correct controller method here
$this->$page();
// A method
public function home(){}
// Another method
public function about(){}
// e.g. ?page=home would call the home() method
EDIT: I've tried several of the suggestions, but what I get is a memory overload error message. Here is my full code:
<?php
class Controller {
// Defines variables
public $load;
public $model;
public function __construct() {
// Instantiates necessary classes
$this->load = new Load();
$this->model = new Model();
if (isset($_GET['page'])) {
$page = $_GET['page'];
$fc = new FrontController; // This is what crashes apparently, tried with and without ();
}
}
}
If I understand your question correctly, you'd probably want something more like this:
class FrontController {
public function home(){ /* ... */ }
public function about(){ /* ... */ }
}
$page = $_GET['page'];
$fc = new FrontController;
if( method_exists( $fc, $page ) ) {
$fc->$page();
} else {
/* method doesn't exist, handle your error */
}
Is this what you're looking for? The page will look at the incoming $_GET['page'] variable, and check to see whether your FrontController class has a method named $_GET['page']. If so, it will be called; otherwise, you'll need to do something else about the error.
You can call dynamic properties and methods using something like this:
$this->{$page}();
Use a class.
Class URLMethods {
public function home(){ ... }
public function about(){ ... }
}
$requestedPage = $_GET['page'];
$foo = new URLMethods();
$foo->$requestedPage();
You can achieve this by using call_user_func. See also How do I dynamically invoke a class method in PHP?
I think you'd like also to append another string to the callable functions like this:
public function homeAction(){}
in order to prevent a hacker to call methods that you probably don't want to be.
I have made a class in php which is goind to be inherited by another class in the other folder.
when i put echo $this->protectedvariableofclass; //in subclass function
it gives no value
remember my base class is stored \class\user.php
sublass is stored as \model\model_user.php
Please help me out
Thanks in advance
Base Class in \class\user.php
<?php
class user
{
protected $user_id;
//setter method
public function set_user_id($user_id)
{
$this->user_id=$user_id;
}
//getter method
public function get_user_id()
{
return $this->user_id;
}
}
?>
Subclass in \model\model_user.php
<?php
require_once 'class/user.php';
class model_user extends user
{
public function checkUser()
{
echo $this->user_id;
$sql = "SELECT * FROM user WHERE user_id='$this->user_id'";
$result = mysql_query($sql);
if(!result)
{
die('error'.mysql_error());
}
$duplicates = mysql_num_rows($result);
if($duplicates > 0)
return 1;
else
return 0;
}
}
Maybe you have done this already, but in case you're not, try this:
$model_user = new model_user();
$model_user->set_user_id(5);
$model_user->checkUser(); // Should output 5
Everything I see is that you're trying to output user_id which is not assigned anywhere in the posted code.