baileyJchoi baileyJchoi - 24 days ago 7
PHP Question

PHP require not working

When I go to my site, it is supposed to redirect me to google.com

Here is my structure:

application
-config
-Application.php
-Router.php
public
-index.php


Here is my code:

index.php:

require '../application/config/Application.php';
$app = new Application();


Application.php:

<?php
require dirname(__DIR__).'config/Router.php';

class Application {

private $router = new Router();

public function __construct() {
$this->router;
}

}
?>


Router.php;

class Router {

public function __construct() {
header('Location: https://www.google.com');
}

}


I want it to redirect from index -> to Application.php -> to Router.php -> redirect to google.com in construct.

EDIT: I know it gets to Application.php because if I put the
header
in the Application.php construct, it redirects. it's just not getting to the Router.php

Why am i doing all of this? because I want to test if everything is working first.

Answer

private $router = new Router(); isn't going to work. You'll need to assign it in the constructor instead.

class Application {

    private $router;

    public function __construct() {
        $this->router = new Router();
    }

}

From the PHP documenation on 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.

new Router() is not able to be evaluated at compile time.


Also, require dirname(__DIR__).'config/Router.php'; looks like it will cause you problems, as dirname(__DIR__) won't have a trailing slash.

You would be a lot better off with this sort of debugging if you enabled error reporting. The errors do a pretty good job of telling you where the problems lie, and without them your debugging will just be doing a lot of shooting in the dark.