I want PHP to construct an object by indirect variable reference within namespaces.
It goes like:
$ArticleObjectIdentifier = 'qmdArticle\excursions_list_item';
$result = new $ArticleObjectIdentifier($parent_obj,$r);
Where qmdArticle is a namespace used and excursions_list_item
is the class name - which is usually not hardcoded but read from DB.
I get the following error - when using the above:
Class 'qmdArticle\\excursions_list_item' not found in /media/work/www/mytestarea/control.php on line 1916 ...
index.php
<?php
namespace hy_soft\qimanfaya\testarea\main;
use hy_soft\qimanfaya\testarea\articles as article;
include_once('article.php');
$ArticleLoader = 'article\excursions_list_item';
$article = new $ArticleLoader();
$article->showcontent();
?>
article.php
<?php namespace hy_soft\qimanfaya\testarea\articles
class excursions_list_item { private $content; function
__construct() {
$this->content = 'This is the article body';
// parent::__construct($parent,$dbrBaseRec);
}
public function showcontent() { echo $this->content; } }
?>
I finally have found a similar example but it took a while until I actually got it:
The actual trick is using double quotes: >>"<<
AND double-slashes >>\<<
AND it doesn't work with an alias created like
use hy_soft\qimanfaya\testarea\articles as article;
You have to use the fully qualified class name (FQCN)
$ArticleLoader = "\\hy_soft\\qimanfaya\\testarea\articles\\excursions_list_item";
I would still apreciate any advice how to do it with an alias. Thanks.
Working example:
article.php
<?php
namespace hy_soft\qimanfaya\testarea\articles;
class excursions_list_item
{
private $content;
function __construct()
{
$this->content = 'This is the article body';
// parent::__construct($parent,$dbrBaseRec);
}
public function showcontent()
{
echo $this->content;
}
}
?>
index.php
<?php
namespace hy_soft\qimanfaya\testarea\main;
use hy_soft\qimanfaya\testarea\articles as article;
include_once('article.php');
$ArticleLoader = "\\hy_soft\\qimanfaya\\testarea\articles\\excursions_list_item";
//$ArticleLoader = "\\article\\excursions_list_item"; doesn't work
$article = new $ArticleLoader();
$article->showcontent();
?>
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)
In my test. I have defined a class which has getLastTradeTime function
Here is class code:
<?php
namespace model;
//class Trade {//works fine
class Trade Extends \Mysql\Crud {// works fail
protected $table = 'ms_trade';
protected $pk = 'id';
private $hh;// hh is not related to class /Crud
public function getLastTradeTime($uid, $ip) {
$this->hh="stringtest";
return $this->hh;
}
}
Now I want to call this class function, I should get "stringtest" return.
But It is unlucky, there is nothing i have got.
Here is html code:
<body style="height:100%" >
<?php
include "o1ws1v/class/model/Trade.php";
$trade_model = new \model\Trade();
$lastTrade_time = $trade_model->getLastTradeTime("654651","127.0.0.1");
echo $lastTrade_time;
?>
</body>
I mean it is simply class, and normal way to call function. It seems nothing wrong
Who can give me a favor
i am not having namespace model so i removed it.
It seems that something wrong with your path. ("o1ws1v/class/model/Trade.php")
Kindly double check it.
below code is working using below files.
1.Trade.php
<?php
class Trade {
protected $table = 'ms_trade';
protected $pk = 'id';
public function getLastTradeTime($uid, $ip) {
$hh="stringtest";
return $hh;
}
}
?>
2.child.php
<?php
include "Trade.php";
$trade_model = new Trade();
$lastTrade_time = $trade_model->getLastTradeTime("654651","127.0.0.1");
//can also called as below.
//$lastTrade_time = $trade_model::getLastTradeTime("654651","127.0.0.1");
echo $lastTrade_time;
?>
call child file in your server.
if you having any query, feel free to ask.
I created a common.php for my all the global function. When I run my first function {{Common::test()}}
It's working fine But I can not use model in it.
namespace App\library;
{
class Common {
public static function test()
{
echo "Yes";
return "This comes from Common File";
}
public static function getCmsBlocks()
{
$model = Modelname::all();
if($model){
echo "asdad";
}else
{
echo "sadasd";
}
}
}
}
I don't get my output when I run {{Common::getCmsBlocks()}}
If your model is in different namespace than App\library you will need to prefix the model class name with its namespace, otherwise PHP will try to load App\library\Modelname which might not be what you need.
Replace
$model = Modelname::all();
with
$model = \Your\Model\Namespace\Modelname::all();
If you use your Modelname class in multiple place in declared namespace, you can import/alias that using use statement so that you can refer to that class by classname in your code:
namespace App\library;
use Your\Model\Namespace\Modelname;
{
class Common {
public static function getCmsBlocks()
{
$model = Modelname::all(); //this will work now
}
}
}
There is no way to define global use to bused by all namespaces in your file, as use always refers to the namespace being declared.
As above the answer is perfect but just a few addition if you don't want to include namespace everytime on at start of each file
Use this :
\App\ModelName::all();
\App\ModelName1::update(item);
\App\ModelName2::find(1);
give path like above and there will be no need to use namespace everytime .
Note: above is path to model which is inside App directory . So change accordingly if you are keeping them at separate place .
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?
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