using same namespace php, Call to undefined function - php

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?

Related

PHPUnit Class not found even though it is defined

I'm trying to unit-test my class-function using PHPUnit, but I keep running into Class not found error, even though it is present.
Here's my func.php where the class is defined:
<?php
class func {
public function url($var) {
//do something
return myvalue;
}
?>
And here's funcCase.php where the Test class is defined:
<?php
require 'func.php';
require 'PHPUnit.php';
class funcTest extends PHPUnit_TestCase {
// contains the object handle of the string class
var $box;
// constructor of the test suite
function funcTest($name) {
$this->PHPUnit_TestCase($name);
}
// called before the test functions will be executed
// this function is defined in PHPUnit_TestCase and overwritten
// here
function setUp() {
// create a new instance of String with the
// string 'abc'
$this->box = new func();
}
// called after the test functions are executed
// this function is defined in PHPUnit_TestCase and overwritten
// here
function tearDown() {
// delete your instance
unset($this->box);
}
// test the url
function testurl() {
$result = $this->box->url('myvalue');
$expected = 'myvalue';
echo $result;
$this->assertTrue($result == $expected);
}
}
?>
And the funcTest.php which runs the PHPTestSuite:
<?php
require_once 'funcCase.php';
require_once 'PHPUnit.php';
$suite = new PHPUnit_TestSuite("funcTest");
$result = PHPUnit::run($suite);
echo $result -> toString();
?>
When running the funcTest.php using phpunit funcTest.php I get this error:
TestCase funcTest->testurl() failed: expected TRUE, actual FALSE
Class 'funcTest' could not be found in 'C:\xampp\htdocs\funcTest.php'.
Why am I getting this if the funcTest class is defined and funcCase.php is included in funcTest.php?

trying to use a trait but keeps saying not found

I have a api trait that connects to an external endpoint. I want to use this trait in a class called ProductClass. The trait is in the same folder as the class, but I get a error is I add use ApiTrait in the class. Error says it cannot find the trait, So if I include the trait file at the top of the class file, I get this error, cannot find ApiTrait in
ProductClass\ApiTrait.
If i pass the trait into the constructor I get an error from my index page when I call the ProductClass because I am not passing in the trait. I dont want to pass any params to the constructor just the string top append to the .env endpoint. any clues greatly appreciated
heres my ApiTrait code
<?php
namespace ApiTrait;
require './vendor/autoload.php';
use GuzzleHttp\Client;
trait ApiTrait
{
protected $url;
protected $client;
public function __construct()
{
$this->url = getenv('API_URL');
$this->client = new Client();
}
private function getResponse(String $uri = null)
{
$full_path = $this->url;
$full_path .=$uri;
try {
$response = $this->client->get($full_path);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
}
return json_decode($response->getBody()->getContents(), true);
}
public function getAPIData($uri)
{
return $this->getResponse($uri);
}
}
this is my ProductClass code
<?php
namespace ProductClass;
include_once("ApiTrait.php");
use DataInterface\DataInterface;
class Product implements DataInterface
{
use ApiTrait\ApiTrait
private $api;
public function __construct(ApiTrait\ApiTrait $apiTrait) {
$this->api = $apiTrait;
}
private function getResponse($append, $try) {
$urlAppend = $append;
$good_data = false;
do{
try{
$result = $this->api->getAPIData($urlAppend);
//check data to see if valid
if(!array_key_exists( "error",$result)){
$good_data = true;
return $result;
}
}
catch(Exception $e){
//call api upto 10 times
if($try < 10) {
sleep(1);
getData($append, $try++);
} else { //return a connection error
$api_error['error']='unable to connect to api';
return $api_error;
}
}
} while($good_data === false);
}
public function getData($append, $try = 0)
{
return $this->getResponse($append, $try);
}
}
If you're using an autloader, you shouldn't ever need this:
include_once("ApiTrait.php");
You've got your trait defined in the ApiTrait namespace:
namespace ApiTrait;
trait ApiTrait { ... }
I.e., the trait's full path is \ApiTrait\ApiTrait. If you're using the trait in a namespace other than the one it's defined, then you need to anchor from the root namespace when referring to it, by preceding it with a backslash:
namespace ProductClass;
class Product implements DataInterface
{
use \ApiTrait\ApiTrait;
Otherwise, if you do use ApiTrait\ApiTrait; without the leading backslash, then PHP thinks you're referring to the current namespace, which is ProductClass, yielding \ProductClass\ApiTrait\ApiTrait -- which doesn't exist, hence your error.
You could also do it this way with class aliases:
namespace ProductClass;
use ApiTrait\ApiTrait;
class Product implements DataInterface
{
use ApiTrait;
Also, it looks like you're just putting every class it its own namespace. Don't do that. Use namespaces to group common items, for example, something like this:
namespace Traits;
trait Api { ... }
namespace Traits;
trait Foo { ... }
namespace Traits;
trait Bar { ... }
namespace App;
class Product {
use \Traits\Api;
use \Traits\Foo;
use \Traits\Bar;
}

use main file's variable inside class 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)

Construct an object by indirect variable reference within namespaces

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();
?>

PHP call method from class in other class

Code example:
<?php // class_database.php
class database
{
include("class_validation.php"); //this does not work
$val = new validation() //this does not work
public function login($value)
{
if($val->validate($value))
{
//do something
}
}
}
<?php // class_validation.php
class validation
{
public function validate($value)
{
if($value > 50) return true;
return false;
}
}
How do I delegate the class validation in class database?
I do not wish to inherit (implement or extends) the class validation -> behavior in validation is not to be changed.
I just want to use the methods from validation class. Any OOP solutions?
Thanks in advance
You cant use include inside a class like that! Either include it at the beginning of the file ( my suggestion ) or use it one line before $val = new validation(); call.
class_database.php:
<?php
include("class_validation.php");
class database
{
public function login($value)
{
$val = new validation();
if($val->validate($value))
{
//do something
}
}
}
?>
 
class_validation.php:
<?php
class validation
{
public function validate($value)
{
if($value > 50)
return true;
return false;
}
}
?>
You need to move the include outside the class. PHP does not allow classes within classes.
Try something like this :
Code example:
<?php
include("class_validation.php"); // include outside the class declaration
// class_database.php
class database
{
$val = new validation()
public function login($value)
{
if($val->validate($value))
{
//do something
}
}
}
You can either put the include() outside your class (at the top of your page, class_database.php), or if your using a framework/autoloader you can call it by namespace:
Option 1
<?php
include('class_validation.php');
class database {
}
Option 2
namespace ThisCoolThing;
use \OtherCoolThing\validation;
class database { ... }

Categories