Apple M1 Mac通过Homebrew升级PHP及路径配置问题咨询
Hey there, let's break down how to get this sorted out—you're already halfway there with Homebrew and php@7.4 installed!
First, why does brew upgrade php throw an error?
Homebrew has two types of PHP formulas:
- The generic
phpformula (points to the latest stable PHP version) - Version-specific formulas like
php@7.4(for older supported versions)
You installed php@7.4, not the generic php package, so running brew upgrade php will fail with "Error: php not installed". To upgrade your existing PHP 7.4, use this command instead:
brew upgrade php@7.4
Next, prioritize Homebrew's PHP over macOS's built-in version
Since you're using ZSH (the default shell on modern macOS), you only need to edit your .zshrc file—no need to touch .bash_profile at all. Here's how to set up the PATH correctly:
- Open your
.zshrcfile in a text editor. For ease, use:
open -e ~/.zshrc
(Or use nano ~/.zshrc if you prefer the terminal-based editor.)
- Add these lines to the end of the file. This ensures Homebrew's PHP binaries are checked before macOS's built-in ones:
# Prioritize Homebrew's PHP 7.4 over system PHP export PATH="/opt/homebrew/opt/php@7.4/bin:$PATH" export PATH="/opt/homebrew/opt/php@7.4/sbin:$PATH"
(Note: /opt/homebrew is the correct path for M1/M2 Macs—Intel Macs use /usr/local instead, but since you're on M1, this path is right.)
- Optional: If you use tools that need PHP's libraries (like compiling extensions), add these lines too:
export LDFLAGS="-L/opt/homebrew/opt/php@7.4/lib" export CPPFLAGS="-I/opt/homebrew/opt/php@7.4/include"
- Save and close the file. Then apply the changes immediately in your current terminal session:
source ~/.zshrc
- Verify it worked by checking your PHP version:
php -v
You should now see PHP 7.4.x instead of the system's 7.3.22.
Bonus: Upgrading to a newer PHP version later
If you decide to switch to a newer stable PHP version (like 8.2) down the line, just run:
brew install php
Then update the PATH lines in your .zshrc to point to /opt/homebrew/opt/php/bin and /opt/homebrew/opt/php/sbin instead of the php@7.4 paths.
内容的提问来源于stack exchange,提问作者eskimo

