In PHP how can i check if class exists? - php

So i have this kind of struct function in main class
function __construct(){
$this->conf = $GLOBALS['conf'];
$this->dbi = new dbinfo;
$this->modOpt = new modOptions;
$this->lang = new language;
/** Connect DB extended Class **/
parent::__construct($GLOBALS['connect']);
}
where i define classes, but this classes is into library file which is included at the start of file except one, which is included when post request will appear like this:
if (isset($_POST['delGroup']) && isset($_SESSION['content_viewer']) && $_SESSION['content_viewer']['code'] >= 1){
include_once(realpath(dirname(__FILE__) . '/../..')."/mod/dbinfo/proc.php");
}
so i want add check into my construct function for dbinfo class like this
function __construct(){
$this->conf = $GLOBALS['conf'];
if (isset(new dbinfo))
$this->dbi = new dbinfo;
$this->modOpt = new modOptions;
$this->lang = new language;
/** Connect DB extended Class **/
parent::__construct($GLOBALS['connect']);
}
but this method with if isset does not works, please show me correct way how to check if class exists into file. thanks

Try using, class_exists() http://php.net/manual/en/function.class-exists.php
In your case, looking for dbinfo class do this:
if(class_exists('dbinfo')){
//do something
If your class has a namespace, include the ful namespaced classname.

class_exists('class_name',false);
Set false to true if the function should try too load the class.

Related

Php overloading function issue with Class

I have a called class called ClientPolicy which is like this
class ClientPolicy {
var $serverHost="www.example.com";
var $httpPort = 80;
var $httpsPort = 443;
var $appKey;
var $secKey;
var $defaultContentCharset = "UTF-8";
}
and another class file name SyncAPIClient which looks like this
class SyncAPIClient{
function SyncAPIClient(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
function SyncAPIClient($appKey, $appSecret) {
$this->clientPolicy = new ClientPolicy();
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
My questions are
1.) If you check the function in SyncAPIClient, you will notice that the ClientPolicy class was passed as a parameter before a variable, what does it really mean? What is the essence of passing a class in function parameter?
2.) I am getting an error "Cannot redeclare SyncAPIClient::SyncAPIClient()" in my script log and the reason is that SyncAPIClient function was called twice in SyncAPIClient class. How can I solve this issue? Is there any better way to write this SyncAPIClient function instead of passing it twice?
The author of this script is nowhere to be found and I am left to fix it.
1) Here the $clientPolicy variable that is passed to this function, needs be a ClientPolicy instance.
In this way, if the argument that is passed is different from an instance of ClientPolice class, an error is generated.
function SyncAPIClient(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
https://wiki.php.net/rfc/typed_properties_v2
https://laravel-news.com/php7-typed-properties
2) The error Cannot redeclare SyncAPIClient::SyncAPIClient() is caused because you are trying to declare two functions called SyncAPIClient ().
If in first SyncAPIClient() method you just want save the $clientPolicy in $this->clientPolicy, you can use the magic method __construct. Or just try changing the name of one of the functions, and the problem should be a problem.
class SyncAPIClient{
__construct(ClientPolicy $clientPolicy) {
$this->clientPolicy = $clientPolicy;
}
function SyncAPIClient($appKey, $appSecret) {
$this->clientPolicy = new ClientPolicy();
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
https://www.php.net/manual/en/language.oop5.decon.php
http://www.zentut.com/php-tutorial/php-constructor-and-destructor/
Hope this helps!
I would've fix the code you have like this:
class SyncAPIClient
{
private $clientPolicy = null;
function SyncAPIClient(ClientPolicy $clientPolicy = null)
{
if($clientPolicy instanceof ClientPolicy){
$this->clientPolicy = $clientPolicy;
}else{
$this->clientPolicy = new ClientPolicy();
}
}
public function setAuthParams($appKey, $appSecret) {
$this->clientPolicy->appKey=$appKey;
$this->clientPolicy->secKey=$appSecret;
}
}
This way you can instantiate a SyncAPIClient with or without a ClientPolicy.
Without ClientPolicy:
$syncAPI = new SyncAPIClient();
$syncAPI->setAuthParams($apiKey, $apiSecret);
With ClientPolicy:
$clientPolicy = new ClientPolicy();
$clientPolicy->appKey=$appKey;
$clientPolicy->secKey=$appSecret;
$syncAPI = new SyncAPIClient($clientPolicy);
When using class and functions in combination like
Rtin::
Functions nested inside that class Rtin should have different names than that class name
So you shouldn't have function called rtin
However you can call function from outside the class with it's name
From the error you have may be due to:
function you nested in the class or the function outside the class has a duplicate outside the script itself. Like having function mentioned in included function.php file and also mentioned in the script itself so php get confused because function name is written in two php files at the same time
Example of class
class Rtin{
private $data;
private $results;
public function getResultsType(){
return ........
}
}
To call class use
$q = Rtin::getResultsType($data['name']);
In your example. Adapt it to the example I have provide and review the included files for duplicate function .

Calling PHP Class Function In My Page

I have a class file: we'll call it class.php. The functionality of that is to grab info from an ini file (yeah, I posted the question about security and was given the great suggestion to use either a config file or an ini file to hold the DB information).
Essentially, my class is this:
<?php
class myClass
{
public function getAttached()
{
$file = "../../myFile.ini";
if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
$hoost = $settings['mysqli']['default_host'];
$useer = $settings['mysqli']['default_user'];
$pazz = $settings['mysqli']['default_pw'];
$dbs = $settings['mysqli']['default_db'];
$con = mysqli_connect($hoost ,$useer, $pazz, $dbs);
return $con;
}
}
$obj = new myClass();
$obj->getAttached();
$vals = $obj->getAttached();
//echo $vals; //didn't know if I should echo this or not.
?>
I want to call this in my somePage.php file to make my "mysqli" connection and go from there...
I tried this:
require_once('class.php');
getAttached();
Obviously that didn't work (I knew it wouldn't but - I did it anyway just to see if "maybe"), so - how do I call that function from my class file in the regular php page?
Any thoughts would be appreciated.
Thanks in advance.
You need to make an instance of the class before calling the functions as they're not static.
require_once('class.php');
$myClass = new myClass();
$myClass-> getAttached();
or, like I said above you could make the function static.
public static function myFunction() {
//etc...
}
Then to call it you would use:
require_once('class.php');
myClass::getAttached();
You have to instanciate your class first, the same way you did it in you class.php file:
$myclass = new myClass();
$myClass->getAttached();
Note that if your method can be used without any relation with your class, you could make it static:
public static function getAttached() {
// ...
}
And use it without having to instanciate your class:
myClass::getAttached();
Your getAttached() method within the myClass ,create the instance for the class and call
the function
$call = new myClass();
$call->getAttached();
Given answers are correct, but if you keep your class file as you posted, you have object already in $obj so there is no need to make new one. If it is just temporary you can ignore my post.
One more thing:
$obj->getAttached(); // this line is not needed, as you call this function in next line
$vals = $obj->getAttached();

how to check if object of a class already exists in PHP?

consider the following code scenario:
<?php
//widgetfactory.class.php
// define a class
class WidgetFactory
{
var $oink = 'moo';
}
?>
<?php
//this is index.php
include_once('widgetfactory.class.php');
// create a new object
//before creating object make sure that it already doesn't exist
if(!isset($WF))
{
$WF = new WidgetFactory();
}
?>
The widgetfactory class is in widgetfactoryclass.php file, I have included this file in my index.php file, all my site actions runs through index.php, i.e. for each action this file gets included, now I want to create object of widgetfactory class ONLY if already it doesn't exist. I am using isset() for this purpose, is there any other better alternative for this?
Using globals might be a way to achieve this. The common way to do this are singleton instances:
class WidgetFactory {
private static $instance = NULL;
static public function getInstance()
{
if (self::$instance === NULL)
self::$instance = new WidgetFactory();
return self::$instance;
}
/*
* Protected CTOR
*/
protected function __construct()
{
}
}
Then, later on, instead of checking for a global variable $WF, you can retrieve the instance like this:
$WF = WidgetFactory::getInstance();
The constructor of WidgetFactory is declared protected to ensure instances can only be created by WidgetFactory itself.
This should do the job:
if ( ($obj instanceof MyClass) != true ) {
$obj = new MyClass();
}

call another class's function inside a class

i have 2 classes
for DB
for language
i want to use my language things in the DB
so it outputs the result
ex :
class db_control{
var $db_connection, $lang_var;
//create the function for the connection
function db_connect(){
//define some variables
global $db_host, $db_username, $db_password, $db_name, $lang_var;
$this->db_connection = mysql_connect("$db_host","$db_username","$db_password")or die("can't connect to server with these informations");
//checl that the connection is established
if($this->db_connection){
echo $lang_vars->getvar("$langvals[lang_con_est]");
}
but this
$lang_vars->getvar("$langvals[lang_con_est]");
doesn't work
i mean it outputs many problems
and am sure my problem is that i didn't define my variables and classes correctly
P.S : the language class is in file called language.php and this part is in DB.MySQL.php
EDIT :
this is the language class
class lang_vars{
public static function getvar($variable){
return $variable;
}
}
i want the DB class to display text from the language class
thats why i used
echo $lang_vars->getvar("$langvals[lang_con_est]");
but it doesn't work
cuz when i declare the language class
$lang_vars = new lang_vars;
inside the db_control it shows error unexpected T_something expected T_Function
and when i declare it outside nothing up
hope i made things more clear now
Any reason why you are still using PHP4 syntax?
When creating an instance of the db_control class, pass the object to be stored as $lan_var into the constructor or set it via a dedicated setter. See Dependency Injection.
class DBControl
{
protected $_lang;
public function __construct($lang = NULL)
{
if($lang !== NULL) {
$this->_lang = $_lang;
}
}
public function setLang($lang)
{
$this->_lang = $lang;
}
}
Then do either
$dbControl = new DBControl(new LangThing);
or
$dbControl = new DBControl;
$dbControl->setLang(new LangThing);
Also, get rid of the globals. Pass those in via Dependency Injection too.
Make your language class methods static . Read more here.
class LangClass
{
public static function getvar()
{
// your code here
}
}
Then, you can use its functions without creating objects like this:
$LangClass::getvar("$langvals[lang_con_est]");
This can do the trick.
$lang_vars = new LanguageClassOrWhateverItIsCalled();
$lang_vars->getvar($langvals[lang_con_est]);
But maybe you should think of making it a static method. In that case you can call it with:
LanguageClassOrWhateverItIsCalled::getVar($langvals[lang_con_est]);
You can define the method static like:
public static function getVar() {
// Do something
}
Edit: #SAFAD
You should use the static method for this. To make this work, be sure your class language.php is loaded. To do so just add in the DB.MYSQL.php file the following line:
require_once('language.php');
class db_control {
...
Make sure you have the right path to the language.php file.
Then you should call the method in db_control class like this:
if($this->db_connection){
echo lang_vars::getvar("$langvals[lang_con_est]");
}
Besides, what is the use of a function like this? You should either do:
if($this->db_connection){
echo $langvals[lang_con_est];
}
or change your static getvar method to:
public static function getvar($variable){
return $langvals[$variable];
}
and your function call to:
if($this->db_connection){
echo lang_vars::getvar("lang_con_est");
}

Create a PHP Class -> Create an object of it in another class

I have created a PHP class called formChecker.php. It validates a form. As a Java programmer, I would like to stick with the idea of creating an instance of this class in another class and run it from there. It doesn't seem to be working for me.The following is a demonstration:
class formChecker{
..... validation functions go here
}
class runFormChecker{
.... create instance of formchecker here and use it's methods etc.
}
Can this be done? What I'm thinking of is developing a number of classes that can be run seperately.
GF
I'd rather pass the instance of formChecker (or something that implements a certain interface) to the instance of runFormChecker. see http://en.wikipedia.org/wiki/Dependency_injection
Could be as simple as
interface FormChecker {
public function foo($x);
}
class MyFormChecker implements FormChecker
public function foo($x) {
return true;
}
}
class RunFormChecker {
protected $formChecker=null;
public function __construct(FormChecker $fc) {
$this->formChecker = $fc;
}
// ....
}
$rfc = new RunFormChecker(new MyFormChecker);
Just include the formChecker class file just before the class you want to use it in eg:
include "formChecker.php"
class runFormChecker{
function __construct() {
$obj = new formChecker; // create instance
// more processing............
}
}
If however, you have both classes in one file (which is bad), then no need to include the file, you can create the instance of that straight away eg:
class formChecker{
// ............
}
class runFormChecker{
function __construct() {
$obj = new formChecker; // create instance
// more processing............
}
}
More Information Here....
Thanks :)
Yes, and this is not strange. You would usually create the instance of formChecker within an instance of runFormChecker though, and not at the class level.

Categories