Home > Blockchain >  How can I specify the relative path in php?
How can I specify the relative path in php?

Time:12-16

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',
    ]);
}

CodePudding user response:

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

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

CodePudding user response:

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/`
  •  Tags:  
  • php
  • Related