Hello i looking for a way to call class function from another class.
i've tried diffrent PHP ways such as the classic way, to call class from class.
http://pastebin.com/X5VfaChr
require_once "user.php";
$user = new UserAction();
class htmloutput{
public function WebSite(){
$user->Moshe();
}
}
Its shows me this error:" syntax error, unexpected 'new' (T_NEW), expecting function (T_FUNCTION)" i dont know about more ways to call a class.
I'll be happy to get helping and
learn somethin' from that.
Have Good day,
Baruch
Besides the comment from Abhik Chakraborty, this fixes the issue coming next:
It's all about scope. Google for DI injection:
require_once "user.php";
$user = new UserAction();
class htmloutput {
public function WebSite(UserAction $user) {
$user->Moshe();
}
}
Try to get the instance inside your function, as the following:
require_once 'user.php';
class htmloutput {
public function WebSite(){
$user = new UserAction();
$user->Moshe();
}
}
Related
I need to use method from Nette library, that I'm including by use command. But it doesn't work as I want to, throws fatal error, that I am calling undefined method.
How should I approach that method to make it work? Stupid question, but I am kinda new to OOP...
Method from class PresenterComponent.php
public function getPresenter($need = TRUE)
{
return $this->lookup('Nette\Application\UI\Presenter', $need);
}
And my code, where I need to use that method:
use Nette\Application\UI\PresenterComponent;
class DatabaseCollectionAdapter extends ArrayDataAdapter
{
// ..... some code......
$this->user = $this->getPresenter()->getUser();
Error:
Fatal Error
Call to undefined method Ctech\Gridator\DataAdapter\DatabaseCollectionAdapter::getPresenter()
change this
$this->user = $this->getPresenter()->getUser();
to this:
$object = new yourObject(); // yourObject extends PresenterComponent
$this->user = $object->getPresenter()->getUser();
use Nette\Application\UI\PresenterComponent; does not include or do any kind of magic to make it's functions available on the fly.
https://secure.php.net/manual/de/language.namespaces.importing.php
It's just a shorthand that helps you to use PresenterComponent directly without specifying the whole namespace.
Your DatabaseCollectionAdapter or ArrayDataAdapter has to have a function that looks like this:
class AdapterClass
public function getPresenter() {
return new Nette\Application\UI\PresenterComponent;
}
}
or something like this
use Nette\Application\UI\PresenterComponent;
class AdapterClass
public function getPresenter() {
return new PresenterComponent;
}
}
I am expecting this to be a basic syntax error I overlooked, but I can't figure it out.
In a PHP script, I keep getting the following error.
Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in [path]/scripts/users/database_connection.php on line 4
This occurs when my script to connect to the database is called with an include_once(). I stripped my script down to the most basic code (leaving in what is required by other code), and it still is calling this error.
<?php
class UserDatabaseConnection
{
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
public function lookupUser($username)
{
// rest of my code...
}
}
$udb = new UserDatabaseConnection;
?>
I have struggled with this for a while, and just wondered if anyone else could spot somewhere I went wrong.
You can not put
$connection = sqlite_open("[path]/data/users.sqlite", 0666);
outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.
You cannot use function calls in a class construction, you should initialize that value in the constructor function.
From the PHP Manual on class properties:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
A working code sample:
<?php
class UserDatabaseConnection
{
public $connection;
public function __construct()
{
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
public function lookupUser($username)
{
// rest of my code...
// example usage (procedural way):
$query = sqlite_exec($this->connection, "SELECT ...", $error);
// object oriented way:
$query = $this->connection->queryExec("SELECT ...", $error);
}
}
$udb = new UserDatabaseConnection;
?>
Depending on your needs, protected or private might be a better choice for $connection. That protects you from accidentally closing or messing with the connection.
Use access modifier before the member definition:
private $connection;
As you cannot use function call in member definition in PHP, do it in constructor:
public function __construct() {
$this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
}
put public, protected or private before the $connection.
check that you entered a variable as argument with the '$' symbol
We should keep our content inside public/private functions only. We can keep content outside of a function.
I've not written OOP code before, I always tried to avoid the extra keystrokes. Anyway, I'm taking the plunge as it's supposed to increase readability.
Anyway, I'm having trouble getting my classes to be able to access each other's methods.
Here's my setup:
$conf = new Conf(); // boot up!
// Include dependencies, system files and other functions
require_once $conf->getIncludePath() . 'error.php';
require_once $conf->getIncludePath() . 'pool.php';
require_once $conf->getIncludePath() . 'database.php';
require_once $conf->getIncludePath() . 'api.php';
require_once $conf->getIncludePath() . 'user.php';
require_once $conf->getIncludePath() . 'forms.php';
require_once $conf->getIncludePath() . 'page.php';
require_once $conf->getIncludePath() . 'resources.php';
$error = new Error();
$pool = new Pool();
$db = new Database();
$api = new Api();
$user = new User();
$forms = new Forms();
$page = new Page();
$resources = new Resources();
My question is, how do I get it so that a method in User class can run the query method inside Database, to say fetch their information?
I'm aware of using global $db; global $user; etc. inside every method ever, but isn't there a way for me to get to these variables without having to essentially redeclare them every time I want to use them?
Thanks
Piers
Using objects is so much more than just readability.
Without going into a full blown explanation of the reasons behind this, I highly recommend further research into the topic. Starting with why they are used and the problems that they resolve (and cause!).
As for your question:
You have a large number of objects that should really be able to 'talk' to each other.
We could say that the User class is dependent on the Database. To resolve this dependency we need to be able to reference the Database in the context on the User (the correct scope).
There are a few ways to accomplish this, however the common practice would be to define a member variable inside the User class and the set the value of the property using setters and getters. This is known to be injecting the dependencies.
For example:
class User {
protected $database;
public function getDatabase()
{
return $this->database;
}
public function setDatabase(Database $database) {
$this->database = $database;
}
public function getUsers()
{
$sql = 'SELECT * FROM user';
return $this->getDatabase()->execute($sql);
}
}
Your client code would then become:
$db = new Database();
$user = new User();
$user->setDatabase($db);
Please note that the above example is a contrived one at best - Making the User class depending on the Database would be a design decision that will cause you other problems further down the line - Something I think you need to research into.
Use dependency injection!
You could create a new class, DBHandler, that stores an instance of your Database class into every other class you want.
For example:
class DBHandler {
public static $db;
public static function init($db) {
self::$db = $db;
}
}
$db = new Database();
DBHandler::init($db);
Then you just need to inherit from this class, by using the extends keyword.
i.e.:
class User extends DBHandler {
// ... your code here ...
}
This is an example of how you could implement the dependency injection.
The __autoload() function
You don't need to require a class everytime you need if you use the __autoload() function.
For example, you can do this to automatically resolve dependencies:
function __autoload($classname) {
require_once $classname . ".php";
}
Following the tutorial at nettuts+ lead me to write this:
// load configuration
require_once 'includes/class.conf.php';
$conf = new Conf(dirname(__FILE__));
// dependency class
$conf->registerRequiredFile('dependencies');
$dependencies = new Dependencies();
// start registering dependencies
$conf->registerRequiredFile('error');
$error = $dependencies->error = function(){ // error
$error = new Error();
$error->conf = $conf;
return $error;
};
$conf->registerRequiredFile('pool');
$pool = $dependencies->pool = function(){ // error
$pool = new Pool();
$pool->db = $db;
$pool->user = $user;
$pool->error = $error;
// etc. any other dependencies
return $pool;
};
It works perfectly, the first conf file contains the registerRequiredFile method that then require_once a uri based on the parameter given.
Thanks for your help in pointing me in the right direction!
I have a php project that uses some functional elements, and some OOP elements, but it seems mixing the two is causing problems. Here are the files that are causing the errors:
DB.php
<?php
function parse_db_entry($from, &$to){
//Function code here
}
?>
User.php
<?php
require_once 'DB.php';
class User{
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
parse_db_entry($entry, $user);
return $user;
}
}
?>
Everything works as it should, except the call to parse_db_entry which throws:
Fatal error: Call to undefined function parse_db_entry()
I am able to access other things in DB.php, for instance if I made a class it there I am able to instantiate it without error, and if I move the function into User.php, it is functional as well. So what am I doing wrong? Why can't I call this method?
I've figured it out! Thanks to everyone who had ideas, but it seems the problem was something else.
When calling require_once 'DB.php', php was actually getting the file:
C:\xampp\php\pear\DB.php
instead of mine.
This may be a problem exclusive to XAMPP, but a simple rename of my file to DBUtil.php fixed everything.
This is a stretch, and I'm totally taking a shot in the dark here, but...
Are you sure parse_db_entry is in the global or User's namespace?
Note: I added a few lines here and there for testing/debugging.
DB.php:
<?php
namespace anotherWorld; // added this ns for illustrative purposes
function parse_db_entry($from, &$to){
echo 'called it';
}
?>
User.php:
<?php
namespace helloWorld; // added this ns for illustrative purposes
class User {
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
parse_db_entry($entry, $user);
return $user;
}
}
?>
test.php:
<?php
require_once 'DB.php';
require_once 'User.php';
use helloWorld\User;
$a = new User();
$a->load_user('email','pass');
echo 'complete';
?>
Yields Fatal error: Call to undefined function helloWorld\parse_db_entry() in User.php on line 13, however when removing the NS declaration in DB.php (namespace anotherWorld) thereby putting parse_db_entry in global NS it runs just fine.
To verify, use the __NAMESPACE__ constant.
If namespace is a problem, without compromising DB's namespace, here is an updated User.php:
<?php
namespace helloWorld;
use anotherWorld; // bring in the other NS
class User {
//Properties
public function __construct(){
//ctor
}
public static function load_user($email, $password){
$entry = //Make MySQL Request
$user = new User();
anotherWorld\parse_db_entry($entry, $user); // call the method from that NS
return $user;
}
}
?>
I'm very confused about using the parameters through pages with PHP OO.
I'm following a tutorial about creating a framework (it's just like the Zend Framework); but, what I don't understand is when this happens:
Example, the index:
// File: sourcefiles/index.php
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', realpath(dirname(__FILE__)).DS );
define ('APP_PATH',(ROOT.'aplicacion'));
require_once APP_PATH. DS.'Config.php';
require_once APP_PATH. DS.'Request.php';
require_once APP_PATH. DS.'BootStrap.php';
require_once APP_PATH. DS.'Controller.php';
require_once APP_PATH. DS.'View.php';
try
{
BootStrap::run(new Request());
I have:
// File: sourcefiles/controladores/IndexController.php
<?php
class IndexController extends Controller
{
public function __construct() {
parent::__construct();
}
public function indexAction()
{
$this->view->titulo='Homepage';
$this->view->contenido='Whatever';
$this->view->renderizar('index');
}
}
?>
And this:
// file : sourcefiles/aplicacion/View.php
<?php
class View
{
private $controlador;
private $layoutparams;
public function __construct(Request $peticion)
{
$this->controlador = $peticion->getControlador();
}
public function renderizar($vista,$item=false)
{
$rutaview = ROOT.'vistas'.DS.$this->controlador.DS.$vista.'.phtml';
if (is_readable($rutaview))
{
include_once $rutaview;
}
else
{
throw new Exception('Error de vista');
}
}
}
?>
And here is the View:
// file : sourcefiles/vistas/index/index.phtml
<h1>
Vista index..
<?php
echo $this->titulo;
echo $this->contenido;
?>
</h1>
Now my questions are:
How the IndexController can use the line? $this->view->titulo = blabla;
The view class doesn't have a "titulo" attribute; however, I can do that. But here is a curious thing, if I do that after calling the $this->view->renderizar('index'), I get the error.
How does the index.phtml file knows this? echo $this->titulo; because, there isn't a include or require called, it's confusing to me.
When I do a require or include call in a file, the required or included file knows the caller's variables?
If somebody can explain these to me, I would really appreciate it :D
or link me to a discussion on official information about this, or how is this called?
Think of an include or require line as "copy-and-pasting" the code from one file into another. This isn't quite accurate, but it explains part of the behaviour here:
In sourcefiles/aplicacion/View.php you include sourcefiles/vistas/index/index.phtml while inside the function View->renderizar. So all the code in index.phtml gets loaded as though it was happening inside that function too. This is why you can access $this, for instance.
As for referencing $this->view->titulo when you haven't defined it, this is PHP letting you be lazy. Just like any variable, a member on an object will spring into life as soon as you mention it, with only a notice warning that maybe you made a mistake.