简体   繁体   中英

PHP Access Class from Another class with Initializer

Ok, so I am building a web application relying on Zend PHP....

Before having to read everything to describe my nested functions, what I need is to be able to call a function from one class to another, which neither are extended upon another, are already extending a db constructor, which are all independently separate files called by one master initializing script .... (?) ... Thanks in advance, and there is a better example below as to what I mean.

My HTML Page calls a "master" include list which initializes and creates all the instances of all my classes so that all pages have common access to the functions. ie require('app_init.php');

Here is the most important excerpt of app_init.php :

require_once('class-general.php');
require_once('class-users.php');
require_once('class-identities.php');

$general = new General();
$users = new Users($db);
$iden = new Iden($db);

---class-general.php

$general is my basis for stupid common functions I use, as well as the DB constructor that all classes can be extended from.

----class-users.php

<?php 
class Users extends General{
public function getUserID(){....random block of auth code....  return $randomID#; }
}?>

-----class-identities.php

<?php
class Iden extends General{

public function do_random_change_to_db($with_me){
....random prepared function using $with_me....

$this->logger->log("Someone with UserID: ". /*((?$this?) HERE:)*/  FIXME->getUserID() . " did something : ".$with_me ."." , Zend_Log::INFO);

$success="gucci";
return $success;
}
}?>

Right now, I am being tossed a PHP error for Fatal error: Call to undefined method Iden::getUserID() in ...`

What would be the best way to go about this? I've tried to include one class file with the other one, but i dont exactly want to create a $FIXME= new Users(); either to save on memory space. I also honestly would prefer to not extend any more classes off another at this time.

Thank you in advance.

If the getUserID method does not depend on any instance state (and it doesn't look like it does, though you haven't made it entirely clear), making it static will allow you to call it like so:

Users::getUserID();

If it does depend on instance state, you will need to call it on an instance of the Users class.

It seems to me that General 's methods should actually be static as well, or perhaps even be free functions outside of a class. Remember: classes are used to encapsulate state. If there's no state that needs to be encapsulated, use class (static) methods or simple functions. Do not needlessly complicate your code by introducing objects and inheritance in which those paradigms don't make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM