PHP call method from class in other class - php

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 { ... }

Related

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)

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?

Exposing php functions/library as API in php

I have a library say something like this
function createCompany($json) {
...
}
function readCompany($json) {
...
}
function updateCompany($json) {
...
}
I want to expose them over an API say in the following format
http:// ... /api/api.php?fxn=updateCompany&jsn={"somejson":true}
http:// ... /api/api.php?fxn=readCompany&jsn={"somejson":false}
Is there a direct way were I can directly expose the above methods as API.
I recommend to use classes for security reasons. And you should filter your fxn var. I did a small example for you but the json must be passed via $_POST not via $_GET:
<?php
class myclass {
public function mymethod1($json) {
echo "mymethod1 called with argument:".var_export(json_decode($json),true);
}
public function mymethod2($json) {
echo "mymethod2 called with argument:".var_export(json_decode($json),true);
}
public function mymethod3($json) {
echo "mymethod3 called with argument:".var_export(json_decode($json),true);
}
}
if(isset($_REQUEST['fxn'])) {
$fxn = $_REQUEST['fxn'];
$class = new myclass();
if(method_exists($class, $fxn)) {
$json = isset($_POST['jsn'])?$_POST['jsn']:"";
$class->$fxn($json);
}
}
?>

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.

Another "Yet another call to a member function function() on a non-object"

How come a simple instantiation doesn't work? I have been doing the same method to all of the classes I created/instantiated but this is the only one that's giving me this kind of error.
Fatal error: Call to a member function validate_fname_and_lname() on a non-object in /homepages/......../Validate.php on line 23
Here's my code:
//Class Validate
<?php
require_once 'RegExp.php';
$myRegExp = new RegExp();
class Validate
{
//Sends each entry to corresponding RegExp function with appropriate regular expression
function validate_form($un, $fname)
{
$err_counter = 0;
if(!$this->myRegExp->validate_fname_and_lname($fname))
{
$error_identifier .= 'firstName+';
++$err_counter;
}
}
}
//Class RegExp
<?php
class RegExp
{
function validate_fname_and_lname($flname)
{
return preg_match("/[a-zA-Z' ']{2,}/", $flname);
}
}
I think you are trying to access the global $myRegExp from within object scope.
You should probaby add a constructor to your validator:
public function __construct($re)
{
$this->myRegExp = $re;
}
And then instantiate your Validator like this:
$validator = new Validate($myRegExp);
And you should declare a member variable 'myRegExp' in your Validate class.
And on a side note: I think you should rethink your design. If I were you I'd create an interface:
interface IValidator
{
public function valid($input);
}
Let your specific regex classes implement that interface:
class ValidateFnameAndLname implements IValidator
{
function valid($flname)
{
return preg_match("/[a-zA-Z' ']{2,}/", $flname);
}
}
And construct your Validate class like this:
class Validate
{
protected $myRegExp;
public function __construct(IValidator $validator)
{
$this->myRegExp = $validator;
}
//Sends each entry to corresponding RegExp function with appropriate regular expression
function validate_form($un, $fname)
{
$err_counter = 0;
if(!$this->myRegExp->valid($fname))
{
$error_identifier .= 'firstName+';
++$err_counter;
}
}
}
Then you are on your way to get a more coherent design.
I'm guessing this is the line giving you a problem?
if(!$this->myRegExp->validate_fname_and_lname($fname))
You use $this->myRegExp, but thats not a member of the Validate class. You have $myRegExp declared as a global variable.

Categories