简体   繁体   中英

How can I specify the relative path in php?

I have registration.phtml file in src/Mess/View/pages and registrationView.php in src/Mess/View/Views . How can i specify the relative path to the registration.phtml file in the registrationView.php file? This is code i registrationView.php`

class RegistrationView extends View
{
public ValidationAttributes $validation;

public function __construct(Action $registration)
{
    parent::__construct(src/Mess/View/pages/registration.phtml', [
        'registration' => $registration,
    ]);
    $this->validation = $registration->validationAttributes([
        'login',
        'password',
        'passwordRepeat',
        'firstName',
        'lastName',
        'email',
        'phoneNumber',
        'birthDate',
        'gender',
        'avatar',
    ]);
}

I assume that you use the given string in the parent::__construct as a path.

parent::__construct(__DIR__ . '/../pages/registration.phtml', [
        'registration' => $registration,
]);

You should be getting a parse error because of a missing quote, plus the src directory is by no means a child of Views :

src
    Mess
        View
            pages
                registration.phtml
            Views
                registrationView.php

My advice is that you don't use relative paths, they're very hard to manage when you start nesting includes. You can use the __DIR__ the magic constant and the dirname() function to build absolute paths:

echo dirname(__DIR__) . '/pages/registration.phtml';

Running this from src/Mess/View/Views/registrationView.php will print /path/to/project/src/Mess/View/pages/registration.phtml , which is valid no matter current working directory.

But everything will be easier if you create some utility constants that allow you to forget about relatives paths once and for all, as in:

parent::__construct(PROJECT_ROOT . PAGES . 'registration.phtml', [
    'registration' => $registration,
]);
// PROJECT_ROOT is `/path/to/project/`
// PAGES is `pages/`

Or just:

parent::__construct(PAGES . 'registration.phtml', [
    'registration' => $registration,
]);
// PAGES is `/path/to/project/src/Mess/View/pages/`

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